First of all, I'm very very new to Python/Django but I've using other technologies for years.
In a website where users can create Publications (let's think of Amazon for example), I have a Publication
object that contains the basic stuff, such as title, details, price, etc.
I want, however, to include certain properties that are particular to object type (cloth would have size, color, for men/for women; cars would have brand, model, engine, transmission, etc). The idea is to use Haystack/Elasticsearch to do faceting on those properties, depending on what the user is searching for.
So, here's the basic model:
# main publication class
class Publication(models.Model):
OBJECT_TYPE = (
('cloth', 'Cloth'),
('electronics', 'Electronics'),
('car', 'Cars'),
)
object_type = models.CharField(max_length=30,
choices=OBJECT_TYPE,
default='electronics')
title = models.CharField()
details = models.CharField()
# other fields...
# Haystack index
class PublicationIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
object_type = indexes.CharField(faceted=True, model_attr='object_type')
# other fields...
The question is, where should I store those other properties?
One option would be to have another class/model with the details and an FK to the publication. If so, how should I build the index then? Another option would be to put all the properties for all the publications in the Publication
model, that would be the simplest but probably not elegant.
Another option would be to do inheritance to have CarPublication
, ClothPublication
, etc. If so, the question would be, how do I handle the basic stuff to avoid duplicating all the screens one for each publication type.
I will have only 3 publication types and I don't think I'll be adding more, so doing the inheritance, for example, is a doable option (Amazon has hundreds of categories so it's different).
What would be the best approach?
FYI, using Python 3, Django 1.9, Haystack 2.5-dev, Elasticsearch.
django-polymorphic handles this beautifully.
From the docs:
from polymorphic.models import PolymorphicModel
class Project(PolymorphicModel):
topic = models.CharField(max_length=30)
class ArtProject(Project):
artist = models.CharField(max_length=30)
class ResearchProject(Project):
supervisor = models.CharField(max_length=30)
>>> Project.objects.create(topic="Department Party")
>>> ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner")
>>> ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter")
# Get polymorphic query results:
>>> Project.objects.all()
[ <Project: id 1, topic "Department Party">,
<ArtProject: id 2, topic "Painting with Tim", artist "T. Turner">,
<ResearchProject: id 3, topic "Swallow Aerodynamics", supervisor "Dr. Winter"> ]