简体   繁体   中英

Should I constantly use Django select_related and prefetch_related?

Should I constantly use Django select_related or prefetch_related every time when I use models with OneToMany relations?

If I have multiple foreign keys. Can I use it, like this?

class A(models.Model):
   pass

class B(models.Model):
   pass

class C(models.Model):
   a = models.ForeignKey(A)
   b = models.ForeignKey(B)

# example usage
for entry in C.objects.all().select_related('a').select_related('b'):
   pass

You could also use it like this:

for entry in C.objects.select_related('a', 'b').all():
   pass

And you should use it only when you want to get the foreign keys to make operations with them in another case you shouldn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM