在下面的代码中,如何过滤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

最佳答案

如果将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

关于python - Django数据库:如何根据其他对象的字段过滤对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51808979/

10-14 17:58
查看更多