I have a django model with a couple of subtypes which until now I've been handling explicitly. Each record is uniquely identified by three fields:
class Entity:
type = CharField(max_length=3)
released_at = DateTimeField()
number = IntegerField()
I use a query expression to combine this into a single string for searching and annotating results:
entity_uid_expr = Case(
When(
number=None,
then=Value(None),
),
default=Concat(
'type', ExtractYear('released_at'), 'number',
output_field=CharField()
),
output_field=CharField()
)
This has worked well so far but the two subtypes are diverging quite drastically now and it would be easier to handle those as subclasses using the polymorphic model. What I'm trying to do is something like this:
class Entity:
released_at = DateTimeField()
number = IntegerField()
class EntityA(Entity):
type = 'A'
class EntityB(Entity):
type = 'B'
But this removes the type information from the DB and breaks the query expression.
Is it possible to set a field's default based on the polymorphic class? The only other alternative I can think of is hiding it from visibility and autopopulating it with the right value on save.
Would that be a viable approach or am I missing something?
Thanks!
The solution was pretty simple: I just needed to use the polymorphic type data instead of my own hand built types, which provides the same uniqueness/sorting/filtering I need.
I then removed my
typefield from the model and added a pretty-print method to handle referencing the type label on the class.