Django access to subclasses items from abstract class

2024/10/8 14:50:57
class Animal(models.Model):....class Meta:abstract = Trueclass Cat(models.Model, Animal):...class Dog(models.Model, Animal):....

I want to be able to return all instances of querysets of all the subclasses of Animal. Lets say I have a function called allData which returns an array/list of all the subclasses querysets.

For example:

x = animal.allData()[0] # should return the first element in the array.

I don't mind how we do this, using modules like django-model-utils or not. I just want to be able to return all the subclasses querysets.

Answer

This is not possible in one query. You have two options, one use to use django-model-utils or you can use django_polymorphic.

Polymorphic is better suited to your task, however django-model-utils is made by a very prominent member of the django community and as such has a lot of good support.

If I had to choose, I'd choose django-model-utils since its made by a member of the django team, and thus will be supported. Polymorphic is supported by divio, which is a private company that heavily uses django based in Switzerland.

As for how to select Sub-classes. You need to do two things using django-model-utils. Firstly, you need to change the objects variable in your model to InheritanceManager() like so (adapted from docs):

from model_utils.managers import InheritanceManagerclass Place(models.Model):# ...objects = InheritanceManager()class Restaurant(Place):# ...class Bar(Place):# ...nearby_places = Place.objects.filter(location='here').select_subclasses()
for place in nearby_places:# "place" will automatically be an instance of Place, Restaurant, or Bar

The code above will return all Bars and Restaurants because it uses the select_subclasses.

https://en.xdnf.cn/q/70110.html

Related Q&A

Django BinaryField retrieved as memory position?

Ive written a short unit test with the following code:my_object = MyObject() my_object.data = b12345my_object.save() saved_object = MyObject.objects.first()assert saved_object.data == my_object.datawhe…

difflib.SequenceMatcher isjunk argument not considered?

In the python difflib library, is the SequenceMatcher class behaving unexpectedly, or am I misreading what the supposed behavior is?Why does the isjunk argument seem to not make any difference in this…

PyCharm Code Folding/Outlining Generates Wrong Boundaries

Im having a very frustrating issue with PyCharm in that it does not want to properly outline the code so that blocks fold correctly. Ive looked all over the place and couldnt find any help with this pa…

How to clear the conda environment variables?

While I was setting an environment variable on a conda base env, I made an error in the path that was supposed to be assigned to the variable. I was trying to set the $PYSPARK_PYTHON env variable on th…

Create duplicates in the list

I havelist = [a, b, c, d]andnumbers = [2, 4, 3, 1]I want to get a list of the type of:new_list = [a, a, b, b, b, b, c, c, c, d]This is what I have so far:new_list=[] for i in numbers: for x in list: f…

cxfreeze aiohttp cannot import compat

Im trying to use cx_freeze to build a binary dist for an web application written in Python 3 using the aiohttp package.Basically I did:cxfreeze server.pyand got a dist outputBut when running the ./serv…

Python open() requires full path [duplicate]

This question already has answers here:open() gives FileNotFoundError / IOError: [Errno 2] No such file or directory(11 answers)Closed 9 months ago.I am writing a script to read a csv file. The csv fil…

Pandas to parquet file

I am trying to save a pandas object to parquet with the following code: LABL = datetime.now().strftime("%Y%m%d_%H%M%S") df.to_parquet("/data/TargetData_Raw_{}.parquet".format(LABL))…

Wildcard in dictionary key

Suppose I have a dictionary:rank_dict = {V*: 1, A*: 2, V: 3,A: 4}As you can see, I have added a * to the end of one V. Whereas a 3 may be the value for just V, I want another key for V1, V2, V2234432, …

How to read emails from gmail?

I am trying to connect my gmail to python, but show me this error: I already checked my password, any idea what can be? b[AUTHENTICATIONFAILED] Invalid credentials (Failure) Traceback (most recent cal…