Django prefetch_related from foreignkey with manytomanyfield not working

2024/9/22 17:29:59

For example, in Django 1.8:

class A(models.Model):x = models.BooleanField(default=True)class B(models.Model):y = models.ManyToManyField(A)class C(models.Model):z = models.ForeignKey(A)

In this scenario, C.objects.all().prefetch_related('z__b_set') doesn't work.

Is there a way to prefetch the information I need for c[0].z.b_set.all() to work without an extra query?

Answer

You can use select_related to follow the first part of the relationship (C.z's ForeignKey) in one batch:

C.objects.all().select_related('z').prefetch_related('z__b_set')

The prefetch_related part, however, will be done in at least two queries, as stated in the docs:

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey.

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

Related Q&A

Running SimpleXMLRPCServer in separate thread and shutting down

I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and…

Clean Python multiprocess termination dependant on an exit flag

I am attempting to create a program using multiple processes and I would like to cleanly terminate all the spawned processes if errors occur. below Ive wrote out some pseudo type code for what I think …

Any limitations on platform constraints for wheels on PyPI?

Are there any limitations declared anywhere (PEPs or elsewhere) about how broad a scope the Linux wheels uploaded to PyPI should have? Specifically: is it considered acceptable practice to upload li…

Match set of dictionaries. Most elegant solution. Python

Given two lists of dictionaries, new one and old one. Dictionaries represent the same objects in both lists. I need to find differences and produce new list of dictionaries where will be objects from n…

Cookies using Python and Google App Engine

Im developing an app on the Google App Engine and have run into a problem. I want to add a cookie to each user session so that I will be able to differentiate amongst the current users. I want them all…

Matplotlib animations - how to export them to a format to use in a presentation?

So, I learned how to make cute little animations in matplotlib. For example, this:import numpy as np import matplotlib import matplotlib.pyplot as pltplt.ion()fig = plt.figure() ax = fig.add_subplot(…

Where is python interpreter located in virtualenv?

Where is python intrepreter located in virtual environment ? I am making a GUI project and I stuck while finding the python interpreter in my virtual environment.

Tkinter check which Entry last had focus

I am working on a program that has a virtual keyboard I created using Tkinter. The pages that have the keyboard enabled have entry widgets where the users need to input data. I am using pyautogui as …

Python Popen grep

Id like Popen to execute:grep -i --line-buffered "grave" data/*.txtWhen run from the shell, this gives me the wanted result. If I start, in the very same directory where I test grep, a python…

Url structure and form posts with Flask

In Flask you write the route above the method declaration like so: @app.route(/search/<location>/) def search():return render_template(search.html)However in HTML the form will post to the url in…