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

后端 未结 1 1128
栀梦
栀梦 2020-12-23 03:18

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.Mod         


        
相关标签:
1条回答
  • 2020-12-23 04:10

    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
        )
    
    0 讨论(0)
提交回复
热议问题