简体   繁体   中英

Django prefetch_related on an implicit relation

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-

  • is there a way to somehow tell django that there's a relationship here without explicitly having a many-to-many field with its through table, so I can use select_related?
  • or is there a way to do the JOIN between the objects when I fetch the users (this would be a cross join I think, but it would be better than what I've got now.)

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.

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