Let's say that I'm making an address book app.
class AddressBookEntry(models.Model):
address_book = models.ForeignKey(AddressBook)
name = models.CharField()
email = models.EmailField()
class User(models.Model):
name = models.CharField()
email = models.EmailField()
Both of these objects have an email field. Now I want to find all the address books that a given user appears in. So I make a method on User like
def entries(self):
return AddressBookEntry.objects.filter(email=self.email)
That works fine, but when I'm fetching a few users I need to execute a DB query once per user. I'd like to do User.objects.all().prefetch_related('entries')
, but this doesn't work as entries
is a method, not a ForeignKey.
So-
The more 'Django' way to do it would be to have an explicit relation field:
class AddressBookEntry(models.Model):
address_book = models.ForeignKey(AddressBook)
name = models.CharField()
user = models.ForeignKey("User", related_name="entries")
class User(models.Model):
name = models.CharField()
email = models.EmailField()
User.objects.all().select_related('entries')
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.