开发者

Django best practice with model relationships

开发者 https://www.devze.com 2023-02-11 07:47 出处:网络
class Category(models.Model): name = models.CharField(max_lenth=50) class SubCatergory(models.Model): parent_category = models.ForeignKey(Category)
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.


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.


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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号