django - 注释在不存在的值上返回 null,我想将其转换为 null 为空字符串

标签 django string django-rest-framework null annotate

我有两个模型,客户和采购。我想退回客户购买的最后一家商店并在此订购。

我可以成功显示此列表,显示客户购买的最后一家商店,并能够使用以下模型,查询/子查询,按商店名称订购。

# 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相反,我也认为这就是您的查询为空的原因。

话虽如此,您实际上并不需要 SubqueryOuterRef为了这。相反,您可以使用 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/

相关文章:

python - Django `python manage.py runserver` 不支持 asyncio&aiohttp

python - 如何添加不在模型中的字段 Django Rest Framework

java - 在 Android、Eclipse 中打印字符串数组

Django Rest 框架,如何在 ModelSerializer 中包含 '__all__' 字段和相关字段?

django - 来自 rest_framework modelSerializer 的模型方法

html - 奇怪的 HTML 和 CSS 行为

django - 具有中间模型的 M2M 关系的基于类的 View

python - 统一码编码错误 : 'ascii' codec can't encode character u'\xc5' in position 35: ordinal not in range(128)

java - 将以单个空字节结尾的字节数组转换为 UTF16 编码字符串

C++ 字符串中的回车和换行