Django ManyToMany Attitude

In models.py :

from django.db import models from django.utils.translation import ugettext as _ # Create your models here. class Category(models.Model): name = models.CharField(_(u"Name"), max_length=250) products = models.ManyToManyField("Product", verbose_name=_(u"Products"), \ blank=True, null=True, related_name="+") class Product(models.Model): name = models.CharField(_(u"Name"), max_length=250) category = models.ManyToManyField("Category", verbose_name=_(u"Category"), \ blank=True, null=True, related_name="+") 

On the admin page: m2m relationships

Question:
How can I establish the relationship between the products and category m2m fields in models.py so that on the admin page, as shown in the figure, b2 (product) is marked as belonging to a2 (category).
Any tips on introducing [products, categories] are welcome, thanks.



PS
I am new to Django. Sorry for my English.

+4
source share
1 answer

The problem is that you have two ManyToMany fields. As you noticed, when a connection is established in one of them, it is not in the other.

The solution is simple: drop one of the fields. You only need ManyToManyField on one side of the relationship. Django automatically gives you access to the other side. So, if you saved the categories field in the Product model, you can do my_product.categories.all() to get the categories the product is associated with; and my_category.product_set.all() to get products that belong to the category.

You will also need to drop the related_name="+" attribute: you presumably put this because you are having conflicts that should have been the key.

+6
source

Source: https://habr.com/ru/post/1394798/


All Articles