Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat QuerySets from different models

Tags:

python

django

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?

like image 923
Maciej M Avatar asked Sep 01 '25 10:09

Maciej M


1 Answers

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
like image 88
grrrrrr Avatar answered Sep 03 '25 00:09

grrrrrr