Reputation: 3773
In the code below, how do I filter capital_listings
so to return listings only for capital cities? Also, is it possible to get rid of the intermediate capitals_names
list?
capitals = City.objects.filter(status='capital')
capitals_names = [capital.name for capital in capitals]
capital_listings = Listing.objects.filter #???
Models:
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
Upvotes: 1
Views: 230
Reputation: 23064
If you change Listings.city
to a foreignkey relationship, you can do your query in a single step.
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')
This is explained in the docs:
https://docs.djangoproject.com/en/2.1/topics/db/queries/#lookups-that-span-relationships
Upvotes: 0
Reputation: 524
capital_listings = Listing.objects.filter(city__in=capital_names)
Upvotes: 2