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
capital_listings = Listing.objects.filter(city__in=capital_names)

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

相关内容

  • 没有找到相关文章

最新更新