Nick Bewley
Nick Bewley

Reputation: 9289

Django related_name in Models

Any suggestions on the proper configuration of related_name in models.py to create a category and subcategory structure? Error when running syncdb:

myapp.category: Accessor for field 'parent' clashes with related field 'Category.children'. Add a related_name argument to the definition for 'parent'. myapp.category: Reverse query name for field 'parent' clashes with related field 'Category.children'. Add a related_name argument to the definition for 'parent'. myapp.subcategory: Accessor for field 'parent' clashes with related field 'Category.children'. Add a related_name argument to the definition for 'parent'. myapp.subcategory: Reverse query name for field 'parent' clashes with related field 'Category.children'. Add a related_name argument to the definition for 'parent'.

I'm trying to make a category/subcategory structure. For example, parent categories are soda companies (Coke, Pepsi, etc) and subcategories are types of soda (cola, sparkling water, etc.) A subcategory can be related to different parent categories, and vice versa.

Here are the models that I'm having problems figuring out (using django-mptt):

class Category(MPTTModel):
   site = models.ForeignKey(Site)
   template_prefix = models.CharField(max_length=200, blank=True)
   name = models.CharField(max_length=200)
   parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

       def __unicode__(self):
       return self.name + u' Category'

class SubCategory(MPTTModel):
   name = models.CharField(max_length=50, unique=True)
   parent = TreeForeignKey('Category', null=True, blank=True, related_name='children')

   def __unicode__(self):
       return self.name + u' SubCategory'

Any suggestions are greatly appreciated. Thank you

Upvotes: 0

Views: 1050

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You can't call both the recursive relationship on Category and the FK from SubCategory to Category "children". Pick a different name for one of them.

I must say, though, that this doesn't seem like a good fit for MPTT at all. Companies don't fall into a tree relationship, as they are presumably all on the same level, and neither do soda types: what would it mean for "cola" to be a child of "sparkling water", for example? Sounds like you want a simple ManyToMany relationship from Company to SodaType, so that each company can have many soda types and each type can be made by several companies.

Upvotes: 1

Related Questions