我有两个模型,客户和采购。我想退回客户购买的最后一家商店并在此订购。
我可以成功显示此列表,显示客户购买的最后一家商店,并能够使用以下模型,查询/子查询,按商店名称订购。
# models
class Customer(models.Model):
name = models.CharField(max_length=30)
class Purchase(models.Model):
store = models.CharField(max_length=30)
amount = models.DecimalField(decimal_places=2,max_digits=6)
customerID = models.ForeignKey(Customer, on_delete=models.CASCADE,
related_name='purchases')
order_date = models.DateField()
#viewset
#subquery
purchase_qs = Purchase.objects.filter(customerID=OuterRef("pk")).order_by("-order_date")
queryset = Customer.objects.all().annotate(last_purchase=Subquery(purchase_qs.values('store')[:1]))
ordering_fields = ['last_purchase']
对于零购买的客户,我的当前输出是。
"last_purchase":null
我希望有
"上次购买":""
最佳答案
ForeignKey
字段自动附加 _id
到模型字段的名称,因此您需要使用 customerId_id
引用 ForeignKey
.显然这不是您想要的,因此我建议将该字段重命名为 customer
相反,我也认为这就是您的查询为空的原因。
话虽如此,您实际上并不需要 Subquery
或 OuterRef
为了这。相反,您可以使用 Customer
的反向关系。模型,以及 Max
:
from django.db.models import Max
Customer.objects.select_related('Purchase').annotate(
last_purchase = Max('purchases__order_date')
)
最后,
null
key 默认为 False 所以不用说 null=False
, 并没有意义 blank=True
但是 null=False
.见 this question有关 null
之间的差异的出色解释和 blank
是。更新
Coalesce
函数似乎非常适合这种情况:from django.db.models import Max, Coalesce, Value
Customer.objects.select_related('Purchase').annotate(
last_purchase = Coalesce(Max('purchases__order_date', Value(''))
)
关于django - 注释在不存在的值上返回 null,我想将其转换为 null 为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424751/