[Answer]-Django Span Filter in View

0đź‘Ť

âś…

Always start from the model you actually want to get. If you want Discounts, query that model, using the double underscore syntax to traverse relationships.

Discount.objects.filter(discount_store__store_city__city_name="bursa")

1đź‘Ť

First, in your class Store, the related_name is not “correct”, it should be something like “stores” not “cities” because related_name attribute specifies the name of the reverse relation from the City model back to your model.

Less assume that you changed it.

class Store(models.Model):
    store_id = models.AutoField(primary_key=True)
    store_company = models.ForeignKey('Company', related_name='storecompany')
    store_city = models.ForeignKey('City', related_name='stores', to_field='city_name')

Then, given a city name

your_city = City.objects.filter(city_name='city_name')[0]

stores = your_city.stores.all()
discounts = [store.discountstores.all() for store in stores]
👤levi

Leave a comment