Django数据库:如何根据其他对象的字段过滤对象?

时间:2018-08-12 12:47:28

标签: python django

在下面的代码中,如何过滤capital_listings,以便仅返回首府城市的列表?另外,是否有可能摆脱中间的capitals_names列表?

capitals = City.objects.filter(status='capital')
capitals_names = [capital.name for capital in capitals]
capital_listings = Listing.objects.filter #???

型号:

class Listing(models.Model):
    city = models.CharField(max_length = 30, default = 'placeholder')
    date_added = models.DateTimeField()

    def __str__(self):
        return self.name

class City(models.Model):
    name = models.CharField(max_length = 30, default = 'placeholder')
    status = models.CharField(max_length = 30, default = 'placeholder')

    def __str__(self):
        return self.name

2 个答案:

答案 0 :(得分:2)

capital_listings = Listing.objects.filter(city__in=capital_names)

答案 1 :(得分:0)

如果将Listings.city更改为外键关系,则可以一步完成查询。

class City(models.Model):
    name = models.CharField(max_length = 30, default = 'placeholder')
    status = models.CharField(max_length = 30, default = 'placeholder')

class Listing(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE)


capital_listings = Listing.objects.filter(city__status='capital')

在文档中对此进行了解释:

https://docs.djangoproject.com/en/2.1/topics/db/queries/#lookups-that-span-relationships