How to use reverse relation in my query?(django)
Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to use reverse relation in my query?(django) on this date .
I’m trying to make a query to show all the branches which have the food. I’ve tried a lot but I can’t make it work. Could someone help me?
Here are my models:
class Branch(models.Model): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) is_main = models.BooleanField() description = models.TextField(max_length=500) food_restaurant_category = models.OneToOneField(FoodRestaurantCategory, on_delete=models.CASCADE) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) branch_address = models.OneToOneField(BranchAddress, on_delete=models.CASCADE) manager = models.OneToOneField("accounts.Staff", on_delete=models.CASCADE) class Food(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=upload_path) description = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) meal_category = models.ManyToManyField(MealCategory, related_name="meal") food_restaurant_category = models.ManyToManyField(FoodRestaurantCategory, related_name="food_cat") class Menu(models.Model): inventory = models.PositiveIntegerField() price = models.DecimalField(validators=[MinValueValidator(0.0)], max_digits=10, decimal_places=1) food = models.ForeignKey(Food, on_delete=models.CASCADE, related_name="food_rel") branch = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name="branch_rel")
Answer
You can obtain the Branch
es for which there is a Menu
that links to a Food
object food
with:
Branch.objects.filter(branch_rel__food=food)
It however does not seem to make much sense to specify related_name='food_rel'
and related_name='branch_rel'
since this is the name of the relation in reverse, likely related_name='menus'
, in that case you filter with Branch.objects.filter(menus__food=food)
.