0

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

Jože Kuhar
  • 49
  • 1
  • 6
  • You overthinking it. Look at your database. There will be 5 tables instead of 3. If you don't need any intermediate fields simple one m2m filed will suffice. – Waldemar Podsiadło Jul 31 '23 at 04:49
  • This reminds me of [this post](https://stackoverflow.com/questions/76756397/why-is-django-manytomanyfield-asymmetric). As Waldermar says, the best is to check what really happens in the database, or maybe use [sqlmigrate](https://docs.djangoproject.com/en/4.2/ref/django-admin/#sqlmigrate) to check what the sql statements would do. – Martin Jul 31 '23 at 06:54
  • Actually there are only 3 database tables (_category, _product and _categoryproduct). Except if you meant for attribute_value m2m field but that wasn't part of my question. Trough attribute on m2m field actually prevents django to create its own tables. – Jože Kuhar Jul 31 '23 at 13:56

1 Answers1

2

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

thebjorn
  • 26,297
  • 11
  • 96
  • 138