Home > Back-end >  How can I filter by a polymorphic attribute for an attribute only existing in one class?
How can I filter by a polymorphic attribute for an attribute only existing in one class?

Time:09-09

I'm uncertain how to phrase this question better, so please let me show an example:

I use Django-polymorphic and have this structure:

from polymorphic.models import PolymorphicModel
from django.db import models


class Book(models.Model):
    author = models.OneToOneField(
        "Author",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
    )

class Author(PolymorphicModel):
    name = models.CharField(max_length=20, blank=True)

class AnonymousAuthor(Author):
    known_as = models.CharField(max_length=20, blank=True)

I want to filter for all books by the anonymous author known as "foobar".

I tried:

Book.objects.filter(author__known_as="foobar").all()

but I get:

Cannot resolve keyword 'known_as' into field. Choices are: name.

I can filter for books by anonymous authors like this:

aa_ctype = ContentType.objects.get_for_model(AnonymousAuthor) Book.objects.filter(author__polymorphic_ctype=aa_ctype)

But even with that I cannot filter for books with that name.

How can I filter for all Books by the anonymous author `"foobar"?

It is necessary to do the filtering with Django ORM. In my actual example I need to do this for django-filters.

CodePudding user response:

I found it:

Book.objects.filter(author__anonymousauthor__known_as="foobar").all()

So the pattern is:

{attribute}__{classname in lowercase}__{attribute}

I just tried it and it works like a charm :-)

CodePudding user response:

I think the problem is that your PolymorphicModel is not Book but Author.

So:

class Book(models.Model):
    .....

class Author(PolymorphicModel):
    ....

class AnonymousAuthor(Author):
    ....
  • Related