Home > Software design >  Preload FK relation in different column Django
Preload FK relation in different column Django

Time:01-25

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?

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

CodePudding user response:

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

  •  Tags:  
  • Related