简体   繁体   中英

Filter queryset with reverse relationship in Django

If I have two models

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA, related_name="children")
    status = models.IntegerField()
    date = models.DateTimeField()

I can get the latest ModelB object with ModelA.objects.children.latest('date') but can I also filter my ModelA queryset against fields in the latest ModelB object? I mean something like

ModelA.objects.filter(ModelA.objects.children.latest('date')['status']=1)

or

ModelA.objects.filter(latest_children__status=1)

I know this code wont work but I hope it illustrates what I want.

You can do this

ModelA.objects.filter(children__status=1).latest('children__date')

Filter the objects first then get latest.

Not sure if this is going to work, but give it a try.

ModelA.objects.filter(children__status=1)\
    .annotate(last_date=Max('children__date'))\
    .filter(children__date=F('last_date'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM