Best way to reference two associated models in the third model in Django

Viewed 47

I need to reference Category and SubCategory models in the Product model. But SubCategory has a ForeignKey to Category. Right now I am referencing as shown below. Is there a better way or is this correct?

class Category(models.Model):
    category_name = models.CharField(max_length=250)

    def __str__(self):
        return f'{self.category_name}'

class SubCategory(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    subcategory_name = models.CharField(max_length=250)

    def __str__(self):
        return f'{self.subcategory_name}'

class Product(models.Model):
    company_category = models.ForeignKey(Category, models.SET_NULL, blank=True, null=True)
    company_subcategory = models.ForeignKey(SubCategory, models.SET_NULL, blank=True, null=True)
1 Answers

it depends, can product.company_category be different than product.company_subcategory.category, if the answer is yes then your current setup is correct.

But if those two values will always be the same and you want to keep your tables as normalized as possible, then it might be a good idea to only use company_subcategory.

One caveat to the normalized approach is every time you load an instance of Product and you want to reach product.company_subcategory.category you will generate extra sql queries unless you use the select_related or prefetch_related methods

Product.objects.all().prefetch_related('company_subcategory', 'company_subcategory__category')
Product.objects.select_related('company_subcategory', 'company_subcategory__category').get(pk=1)
Related