4

My models:

class BaseModel(models.Model):
    my_field = models.CharField(max_length=250)

    class Meta:
        abstract = True


class ModelA(BaseModel):
    a_field = models.CharField(max_length=250)


class ModelB(BaseModel):
    def some_function(self):
        return 'some result'

Now i want to perform filtering on queryset, where queryset consists of ModelA.objects.all() and ModelB.objects.all().

I tried:

queryset = chain(ModelA.objects.all(), ModelB.objects.all())

And then:

queryset.filter(my_field='some_string')

But i receive following error:

'itertools.chain' object has no attribute 'filter'

How can i concatenate QuerySets of these two models into one and perform filtering based only on BaseModel fields?

2
  • you can't filter chain in django Commented Mar 1, 2019 at 14:09
  • what exactly you want to do Commented Mar 1, 2019 at 14:10

1 Answer 1

3

To accomplish this you will need to use Multi-Table Inheritance and query the BaseModel instead of an Abstract Base Class

BaseModel.objects.filter(my_field='some_string') 
#returns a queryset of BaseModels

Alternatively there is a third party package called Django Polymorphic that in using the above code will return the subclass models instead of the superclass models. This seems to get you closest to the solution you are looking for. It is a pretty cool package!

BaseModel.objects.filter(my_field='some_string') 
#returns a queryset of ModelAs and ModelBs
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Django Polymorphic was exactly what I was looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.