Rob B
Rob B

Reputation: 1523

Django best practice with model relationships

class Category(models.Model):
    name = models.CharField(max_lenth=50)

class SubCatergory(models.Model):
    parent_category = models.ForeignKey(Category)
    name = models.CharField(max_length=100)

class Product(models.Model):
    sub_category = models.ManytoManyField(SubCatergory) 
    name = models.CharField(max_length=100)

Is the above best practice for organising relationships or should I combine the models for cat/sub cat to make it more like a tagging system? For example a product can be tagged with "Cat A" and "Sub Cat A". The app won't need to have categories added to it after launch.

Upvotes: 1

Views: 407

Answers (3)

Mp0int
Mp0int

Reputation: 18737

For more flexibility, model structure i use for such is like that:

class Category(models.Model):
    parent_category = models.ForeignKey('self', null=True, blank=True)
    name = models.CharField(max_lenth=50)

class Product(models.Model):
    categories = models.ManytoManyField(Catergory) 
    name = models.CharField(max_length=100)

So, if a category do not have a parent_category, then it is a basic one, if it have, then it is a subcategory.

In that hierarchy, you can define infinite depth of category-subcategory hierarchy, but on the view layer, you must write mode lines to get the proper category listing as a tree (such as, first filter the categories with isnull=True, then go down through.). But with a few well coded loops and if checks, you can do it.

Upvotes: 4

Andrew Wilkinson
Andrew Wilkinson

Reputation: 10846

This really depends on your requirements. If you're writing a program for a system that only requires a two-level hierarchy then what you've done is perfectly fine. If you can imagine a time where you might have a more complicated hierarchy then combining them does make sense.

You mention a 'product', which to me suggests that you want a strict hierarchy so your current models seem fine.

Upvotes: 1

damienix
damienix

Reputation: 6763

More flexible will be the code

class Category(models.Model):
    name = models.CharField(max_lenth=50)

class SubCatergory(Category):
    parent_category = models.ForeignKey(Category)

class Product(models.Model):
    categories = models.ManytoManyField(Catergory) 
    name = models.CharField(max_length=100)

Upvotes: 1

Related Questions