如何在我的查询中使用反向关系?(django)

How to use reverse relation in my query?(django)

我正在尝试查询以显示所有有食物的分店。我已经尝试了很多,但我无法让它发挥作用。 有人可以帮助我吗?

这是我的模型:

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")

您可以获得 Branches,其中 Menu 链接到 Food 对象 food与:

Branch.objects.filter(<strong>branch_rel__food=<em>food</em></strong>)

然而,指定 related_name='food_rel'related_name='branch_rel' 似乎没有多大意义,因为这是反向关系的名称,可能是 related_name='menus',在这种情况下,您可以过滤与 Branch.objects.filter(<strong>menus__food=<em>食物</em></strong>).