Stack Overflow Asked by natehawkboss on November 20, 2021
Let me start by stating that I have looked at django-polymorphic for this and still have questions. I have item models and many subtypes for items. Currently, my models look like this.
class Item(models.Model):
pass
class Television(Item):
upc = models.CharField(max_length=12, null=True)
title = models.CharField(max_length=255, null=True)
brand = models.ForeignKey(Brand)
screen_size = models.IntegerField()
class Fridge(Item):
upc = models.CharField(max_length=12, null=True)
title = models.CharField(max_length=255, null=True)
brand = models.ForeignKey(Brand)
stuff_about_fridge = models.CharField(max_length=255, null=True)
I did this at first because then I wouldn’t worry about all of the left joins when querying different item types that would be caused if my models looked like this:
class Item(models.Model):
upc = models.CharField(max_length=12, null=True)
title = models.CharField(max_length=255, null=True)
brand = models.ForeignKey(Brand)
class Television(Item):
screen_size = models.IntegerField()
class Fridge(Item):
stuff_about_fridge = models.CharField(max_length=255, null=True)
I am now reaching a point where I realize that I very often query all of the Item models together and have to left join information from the subtypes instead, so I am not really saving myself there. My question is, even if I used something like django-polymorphic, would it make sense to A) put everything that is shared in the parent model and just specific things in the child models or to B) have it like I do where everything is in the child model, but they share a parent model PK just so that they can be queried together?
"Abstract base classes are useful when you want to put some common information into a number of other models. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class"
Reference: https://docs.djangoproject.com/en/3.0/topics/db/models/#abstract-base-classes
The point of using inheritance is for sharing common info as mentioned in option (A).
Django-polymorphic makes using inherited models easier, nothing more.
Reference: https://django-polymorphic.readthedocs.io/en/stable/
That means, in conclusion, option (A) is correct even though if you use Django-polymorphic.
Below method is the right approach:
class Item(models.Model):
upc = models.CharField(max_length=12, null=True)
title = models.CharField(max_length=255, null=True)
brand = models.ForeignKey(Brand)
class Television(Item):
screen_size = models.IntegerField()
class Fridge(Item):
stuff_about_fridge = models.CharField(max_length=255, null=True)
Answered by Siva Sankar on November 20, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP