首页 > 解决方案 > 如何在 Django 的多对多中执行正确的反向查询

问题描述

我正在尝试对manytomanyDjango 中的字段执行反向查询,但它一直没有给我任何东西,这是我的代码

模型.py

class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=120)
    image = models.ImageField(upload_to='products')
    branch = models.ManyToManyField(Branch, related_name='branches')

class Branch(models.Model):
    area = models.ForeignKey(Area, on_delete=CASCADE)
    name = models.CharField(max_length=1200)
    phone = models.CharField(max_length=30, null=True, blank=True)
    address = models.CharField(max_length=1200, null=True, blank=True)
    tax_value = models.DecimalField(decimal_places=2, max_digits=4)

视图.py


for branch in product_object.branches.all():
    print(branch)

分支总是什么都没有!

标签: pythondjango

解决方案


由于某种原因,相关名称不再调用它。我使用模型名称(小写)调用它。这就是它的工作原理

for branch in product_object.branch.all():

推荐阅读