简体   繁体   中英

Django - Filter queryset by another queryset through related field

Suppose I have the two models below and I want to get a queryset of all developers that have games where the platform field matches a certain value. How would I go about that?

class Developer(models.Model):
    name = models.CharField(max_length=100, default="Unknown")

class Game(models.Model):
    name = models.CharField(max_length=300)
    developer = models.ForeignKey(Developer, related_name="games", on_delete=models.CASCADE)
    platform = models.CharField(max_length=40)

I tried a few approached but can't seem to figure anything out that works.

You can query this with:

Developer.objects.filter().distinct()

Without the .distinct() [Django-doc] , the same developer will be returned multiple times, if they developed multiple Game s for the same platform. If that is not a problem, you can of course omit the .distinct() .

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