我想知道是否可以在不指定 related_name 的情况下为多对多字段创建中间模型,而只是将 ManyToManyField 放在两个模型上。
我正在观看一些关于 Django ORM 的教程,并且讲师明确表示我们不能在两个模型上使用 ManyToManyField (虽然我认为如果 Django 创建自己的表,这是真的,但我不确定我们是否指定自定义中间模型)。
所以这是代码:
class Category(models.Model):
products = models.ManyToManyField("Product", through="CategoryProduct")
name = models.CharField(max_length=255, unique=True)
class CategoryProduct(models.Model):
category = models.ForeignKey("Category", on_delete=models.CASCADE)
product = models.ForeignKey("Product", on_delete=models.CASCADE)
class Meta:
unique_together = ("category", "product",)
class Product(models.Model):
categories = models.ManyToManyField("Category", through="CategoryProduct")
attribute_value = models.ManyToManyField("AttributeValue", related_name="products")
name = models.CharField(max_length=255, unique=True)
我用虚拟数据测试了它,这段代码对我有用:
p = Product.objects.get(id=1)
c = Category.objects.get(id=1)
p.categories.add(1, 2, 3)
c.products.add(1, 2, 3)