Maciej M
Maciej M

Reputation: 786

Concat QuerySets from different models

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?

Upvotes: 4

Views: 86

Answers (1)

grrrrrr
grrrrrr

Reputation: 1425

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

Upvotes: 3

Related Questions