[英]How do I write a Django ORM query where the select table shares a common column with another table?
I'm using Django and Python 3.7. 我正在使用Django和Python 3.7。 I have these two models.
我有这两个模型。 Note they both have a similar field
请注意,它们都有相似的字段
class Article(models.Model):
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE,)
class WebPageStat(models.Model):
objects = WebPageStatManager()
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, )
score = models.BigIntegerField(default=0)
I would like to write a Django ORM query that selects one of the models but does a join on the shared column in order to do a comparison on the "score" field. 我想编写一个Django ORM查询,该查询选择模型之一,但在共享列上进行联接,以便在“得分”字段中进行比较。 I tried the below, but alas the error
我尝试了以下内容,但可惜错误
Article.objects.filter(publisher=webpagestat.publisher, webpagestat.score__gte==100)
File "<input>", line 1
SyntaxError: positional argument follows keyword argument
How do I include the "WebPageStat" table in my join? 如何在联接中包含“ WebPageStat”表?
What you want is easily done in Django by using lookups that span relations . 通过使用跨越关系的查找,可以轻松地在Django中完成所需的操作。 In your example you need to add a way of referencing the related objects in the ORM.
在您的示例中,您需要添加一种在ORM中引用相关对象的方法。 This is donde by setting the
related_name
attribute of the ForeignKey
fields. 这是通过设置在东德
related_name
的属性ForeignKey
领域。 Although this is not strictly necessary it is more clear in this way. 尽管这不是严格必需的,但以这种方式更加清楚。 You can read more about
related_name
and related_query_name
here . 您可以在此处了解有关
related_name
和related_query_name
更多信息。 In short, your models should look like: 简而言之,您的模型应如下所示:
class Article(models.Model):
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, related_name='articles')
class WebPageStat(models.Model):
objects = WebPageStatManager()
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, related_name='stats')
score = models.BigIntegerField(default=0)
Once this is done your query will be carried out by the following code: 完成此操作后,您的查询将由以下代码执行:
Article.objects.filter(publisher__stats__score__gte=100)
What this query is doing in short is selecting every article whose publisher has at least one web page stat whose score is greater than or equal to 100. 简而言之,此查询在选择发布者具有至少一个其得分大于或等于100的网页状态的每篇文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.