Quantcast
Channel: User Ciprian Tarta - Stack Overflow
Viewing all articles
Browse latest Browse all 31

Django triple relation with select/prefetch related?

$
0
0

I have the following models:

class User(models.Model):    ...    @property    def to_dict():        prefs = self.prefs.get()        return {'id': self.pk, 'birthday': prefs.birthday}class UserPref(models.Model):    user = models.ForeignKey(User, rel_class=models.OneToOneRel, related_name='prefs')    birthday = models.DateTimeField()class Item(models.Model):    user = models.ForeignKey(User, related_name='items')    name = models.CharField()    @property    def to_dict():        return {'name': self.name, 'owner': self.user.to_dict}

I need to get all the items for a user and also include user preferences in the response, like so:

items: [{    name: 'item 1',    owner: {        id: 1,        birthday: '11/11/1900'    }}]

My queryset is as follows:

items = Items.objects.all().select_related('user')result = [item.to_dict for item in items]

The problem is that whenever item.to_dict is called, there's a query being done on the UserPref model because of this line prefs = self.prefs.get()

So if I have 20 items, there will be 21 queries instead of 1 with 2 joins.

How can I optimize this?

Note: using prefetch_related instead of select_related, doesn't work.


Viewing all articles
Browse latest Browse all 31

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>