1

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
4
  • 1
    Any reason you're not using a ForeignKey here? Commented Aug 12, 2018 at 12:50
  • docs.djangoproject.com/en/2.1/topics/db/models/#relationships Commented Aug 12, 2018 at 12:52
  • @JonClements: No particular reason. How would I apply it in this case? Commented Aug 12, 2018 at 13:22
  • 1
    The Django tutorial is fairly good - if you have a look at the link that @HåkenLid posted above and the examples in it - that'll explain everything you need for it (and probably more that'll come in handy) Commented Aug 12, 2018 at 13:23

2 Answers 2

2
capital_listings = Listing.objects.filter(city__in=capital_names)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.