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="+")
In admin page:
The question:
How can the relations between products
and category
m2m fields in models.py be set so that in admin-page, as it can be seen at the picture, b2
(the product) was marked as it belongs to a2
(the category).
Any advices for implementation of [products, categories] are welcomed, thank you.
P.S.
I'm newbie in Django. Sorry for my English.
The problem is that you have two ManyToMany fields. As you've noted, when the relationship is set in one of them, it isn't in the other.
The solution is simple: drop one of the fields. You only need a ManyToManyField on one side of the relationship. Django gives you access to the other side automatically. So, if you kept the categories
field on the Product
model, you can do my_product.categories.all()
to get the categories a product is associated with; and my_category.product_set.all()
to get the products that belong to a category.
You'll also need to drop the related_name="+"
attribute: you've presumably put that in because you were getting conflicts, which should have been a clue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With