4đź‘Ť
Why not just have both types of category in one model, so you just have 3 models?
Site
Category
Sites = models.ManyToManyField(Site)
IsCommon = models.BooleanField()
Item
Category = models.ForeignKey(Category)
You say “Internally, those two type of Categories are completely identical”. So in sounds like this is possible. Note it is perfectly valid for a ManyToManyField to have only one value, so you don’t need “ForeignKey and a ManyToMany field on the same Category model” which just sounds like a hassle. Just put only one value in the ManyToMany field
1đź‘Ť
As as alternative implementation you could use django content types (generic relations) to accomplish the connection of the items. A bonus for using this implementation is that it allows you to utilize the category models in different ways depending on your data needs down the road.
You can make using the site categories easier by writing model methods for pulling and sorting categories. Django’s contrib admin also supports the generic relation inlines.
Your models would be as follow:
Site(models.Model):
label = models.CharField(max_length=255)
Category(models.Model):
site = models.ManyToManyField(Site)
label = models.CharField(max_length=255)
SiteCategory(models.Model):
site = models.ForeignKey(Site)
label = models.CharField(max_length=255)
Item(models.Model):
label = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
For a more in depth review of content types and how to query the generic relations you can read here: http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
- [Django]-Django manytomany: adding multiple, non-unique relationships?
- [Django]-Making a query for all objects that don't have `None` for a certain field
- [Django]-Python model inheritance and order of model declaration
- [Django]-How to change the user display name to their first name in Django
0đź‘Ť
Caveat: I know Object-Relation mapping, Rails, and Python, but not Django specifically.
I see two additinal options:
- Thinking from a database point of view, I could make the table needed for the many-many relation hold an additional field which indicates a “common” vs. “site” relationship and add constraints to limit the type of “site” relationships. This can be done in Django, I think, in the section “Extra Fields on Many-To-Many Relationships.”
If you are at an earlier version of Django, you can still do this by making the many-many-table an explict model.
-
Thinking from an object point of view, I could see splitting the Categories into three classes:
BaseCategory
CommonCategory(BaseCategory)
SiteCategory(BaseCategory)
and then use one of Django’s inheritance models.
- [Django]-Django: show useful database data in admin interface?
- [Django]-Sphinx search in django admin