Search code examples
djangodjango-modelsdjango-orm

Django intermediate many-to-many model


I wonder if I can create intermediate model for many-to-many field without specifying related_name but rather just put ManyToManyField on both Models.

I was watching some tutorial on Django ORM and instructor explicitly said we can't use ManyToManyField on both Models (while I think that is true if Django creates own table, I am not sure if it is if we specify custom intermediate model).

So this is the code:

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)

I tested it with dummy data and this code works for me:

p = Product.objects.get(id=1)
c = Category.objects.get(id=1)

p.categories.add(1, 2, 3)
c.products.add(1, 2, 3)

IMPORTANT Question is not about extra M2M field on Product model to attribute_value


Solution

  • That is perfectly fine, although through tables are usually used when you want to store extra data on the CategoryProduct model.