djangogeneric-foreign-key

django: how do I query based on GenericForeignKey's fields?


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)

Still doesn't work. I need to know how to do these kind of queries in django? Thanks.


Solution

  • 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).id
        )