In a project I have inherited I have a few polymorphic models based on a common model. Something like:
from django.db import models
from polymorphic.models import PolymorphicManager, PolymorphicModel
class Product(PolymorphicModel):
name=models.CharField(max_length=127)
objects=PolymorphicManager
class Book(Product):
pass
class Drink(Product):
pass
Personally, I would not use polymorphism, but it’s a bit too late for that and way out of scope. I am tasked with adding translations for the name on the base model using parler, however, the documentation for parler only covers translating fields on the child models.
Nevertheless, I modified the models as such:
from django.db import models
from parler.models import TranslatableModel, TranslatedFields
from parler.managers import TranslatableManager, TranslatableQuerySet
from polymorphic.models import PolymorphicManager, PolymorphicModel
from polymorphic.query import PolymorphicQuerySet
class ProductQuerySet(PolymorphicQuerySet, TranslatableQuerySet):
pass
class ProductManager(PolymorphicManager, TranslatableManager):
queryset_class = MarkerQuerySet
class Product(PolymorphicModel):
translations = TranslatedFields(
name=models.CharField(max_length=127)
objects=ProductManager
class Book(Product):
pass
class Drink(Product):
pass
And it seems to work fine in the django shell:
In [1]: from product.models import Book
In [2]: b0 = Book.objects.first()
In [3]: b0
Out[3]: <Book: A Brief History of Time>
In [4]: b1 = Book()
In [5]: b1.name = 'Hitchhikers Guide to the Galaxy'
In [6]: b1.save()
In [7]: b2 = Book(name='Slaughterhouse V')
In [8]: b2.save()
When I run my endpoint tests, however, I get a somewhat cryptic error:
.venv/lib/python3.12/site-packages/django/db/models/sql/query.py:1577: in _add_q
child_clause, needed_inner = self.build_filter
.
.
.
> arg, value = filter_expr
E ValueError: too many values to unpack (expected 2)
And a different error when I try to see the admin panel for the child models:
Cannot resolve keyword 'name' into field.
I have tried adding a computed properties to the Child models to see if it might fix the admin panel, but it did not. Has anyone any experience with doing something similar?