django:我如何根据GenericForeignKey的字段进行查询? [英] django: how do I query based on GenericForeignKey's fields?
问题描述
我是使用GenericForeignKey的新功能,我无法使其在查询语句中工作。表格大致如下:
I'm new in using GenericForeignKey, and I couldn't make it to work in a query statement. The tables are roughly like the following:
class Ticket(models.Model):
issue_ct = models.ForeignKey(ContentType, related_name='issue_content_type')
issue_id = models.PositiveIntegerField(null=True, blank=True)
issue = generic.GenericForeignKey('issue_ct', 'issue_id')
class Issue(models.Model):
scan = models.ForeignKey(Scan)
扫描会创建一个问题,一个问题会生成一些票证,而且我将问题作为票证表的外键。现在我有一个扫描对象,我想查询与此扫描相关的所有票证。我先试了一下:
A scan creates one issue, an issue generates some tickets, and I made Issue as a foreign key to Ticket table. Now I have a Scan object, and I want to query for all the tickets that related to this scan. I tried this first:
tickets = Tickets.objects.filter(issue__scan=scan_obj)
哪些不起作用然后我尝试这样:
which doesn't work. Then I tried this:
issue = Issue.objects.get(scan=scan_obj)
content_type = ContentType.objects.get_for_model(Issue)
tickets = Tickets.objects.filter(content_type=content_type, issue=issue)
仍然不行。我需要知道如何在django中进行这些查询?谢谢。
Still doesn't work. I need to know how to do these kind of queries in django? Thanks.
推荐答案
您定义的 Ticket.issue
字段帮助您从 Ticket
实例转到附加到的问题
,但不会让您退后。你与第二个例子相近,但你需要使用 issue_id
字段 - 你不能在 GenericForeignKey
(当您有 Ticket
实例)时,它只会帮助您检索对象。尝试这样:
The Ticket.issue
field you've defined will help you go from a Ticket
instance to the Issue
it's attached to, but it won't let you go backwards. You're close with your second example, but you need to use the issue_id
field - you can't query on the GenericForeignKey
(it just helps you retrieve the object when you have a Ticket
instance). Try this:
from django.contrib.contenttypes.models import ContentType
issue = Issue.objects.get(scan=scan_obj)
tickets = Ticket.objects.filter(issue_id=issue.id, issue_ct=ContentType.objects.get_for_model(issue))
这篇关于django:我如何根据GenericForeignKey的字段进行查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!