Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ManyToMany relationship

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:

m2m relationships

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.

like image 547
ted Avatar asked Feb 04 '12 20:02

ted


1 Answers

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.

like image 156
Daniel Roseman Avatar answered Sep 21 '22 07:09

Daniel Roseman