Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Preload FK relation in different column Django

I have Django models that looks like this

class Customer(models.Model):
    name = models.CharField(_("Name"))

class Feature(models.Model):
    label = models.CharField(_("Name"))

class AddOn(models.Model):
    customer = models.ForeignKey(Customer)
    feature = models.ForeignKey(Feature)

Given that I have an instance of Customer e.g

customer = Customer.objects.get(pk=1)

How do I get all the labels in feature in one query to avoid N+1 query?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For now what I’ve done is:

[addon.feature.label for addon in self.addon_set.all()]

But I think for each addon.feature will create a query that is not very optimized if there is a lot of addon

>Solution :

You can use values/values_list to get all labels in a single query

self.addon_set.values_list('feature__label', flat=True)

EDIT: Example of the ManyToManyField

class Customer(models.Model):
    name = models.CharField(_("Name"))
    features = ManyToManyField('Feature', through='AddOn')

class Feature(models.Model):
    label = models.CharField(_("Name"))

class AddOn(models.Model):
    customer = models.ForeignKey(Customer)
    feature = models.ForeignKey(Feature)

You can then perform queries like customer_obj.features.all() or feature_obj.customers.all() and it won’t affect your ability to still query the AddOn model

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading