Django将字段值注释为queryset [英] Django annotate a field value to queryset

查看:90
本文介绍了Django将字段值注释为queryset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字段值(id)附加到如下所示的QS上,但是Django抛出了一个'str'对象,该对象没有属性'lookup'错误。

I want to attach a field value (id) to a QS like below, but Django throws a 'str' object has no attribute 'lookup' error.

Book.objects.all().annotate(some_id='somerelation__id')

似乎我可以使用Sum()获得ID值

It seems I can get my id value using Sum()

Book.objects.all().annotate(something=Sum('somerelation__id'))

我想知道没有办法简单地注释原始字段值到QS?

I'm wondering is there not a way to simply annotate raw field values to a QS? Using sum() in this case doesn't feel right.

推荐答案

至少有三种方法可以访问sum()。

There are at least three methods of accessing related objects in a queryset.


  1. 使用Django的双下划线连接语法:

    如果您只想使用在SQL查询中将相关对象作为条件,您可以在相关对象 related_object 中引用字段 field ,其中 related_object__field 。 Django文档在字段查找下列出了所有可能的查找类型。

  1. using Django's double underscore join syntax:
    If you just want to use the field of a related object as a condition in your SQL query you can refer to the field field on the related object related_object with related_object__field. All possible lookup types are listed in the Django documentation under Field lookups.

Book.objects.filter(related_object__field=True)


  • 使用带有 F()的注释:

    通过使用 F()对象。 F()表示模型的字段或带注释的字段。

  • using annotate with F():
    You can populate an annotated field in a queryset by refering to the field with the F() object. F() represents the field of a model or an annotated field.

    Book.objects.annotate(added_field=F("related_object__field"))
    


  • 访问对象属性:
    一旦评估了查询集,就可以通过该对象上的属性访问相关对象。

  • accessing object attributes: Once the queryset is evaluated, you can access related objects through attributes on that object.

    book = Book.objects.get(pk=1)
    author = book.author.name  # just one author, or…
    authors = book.author_set.values("name")  # several authors 
    

    这会触发附加查询,除非您使用 select_related()

    This triggers an additional query unless you're making use of select_related().

    我的建议是使用解决方案2,因为您已经在那条路的一半处,我认为它将为您提供所要的东西。您现在面临的问题是您没有指定查找类型,而是传递了一个字符串( somerelation_id )Django不知道该怎么做。

    My advice is to go with solution #2 as you're already halfway down that road and I think it'll give you exactly what you're asking for. The problem you're facing right now is that you did not specify a lookup type but instead you're passing a string (somerelation_id) Django doesn't know what to do with.

    此外,有关anateate()的Django文档非常简单。您应该再次调查该问题。

    Also, the Django documentation on annotate() is pretty straight forward. You should look into that (again).

    这篇关于Django将字段值注释为queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆