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