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

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
    )

Leave a Comment