Home > OS >  Django admin prefetch related on property
Django admin prefetch related on property

Time:09-16

I have models Merchant and PhoneNumber. PhoneNumber has a foreign key to Merchant, and Merchant has property business_phone_number which fetches the first phone number in the set of the phone numbers. In Django admin, for the Merchant model, I have business_phone_number in list_display. Although I've put prefetch_related(phonenumber_set), it still queries PhoneNumber 100 times. What am I doing wrong? Here's the simplified code:

class PhoneNumber(models.Model):
    ...
    merchant = models.ForeignKey("merchant.Merchant", on_delete=models.SET_NULL, null=True, blank=True)
    ...
    
class Merchant(models.Model):
    ...
    ...
    @property
    def business_phone_number(self):
        number = self.phonenumber_set.first()
        if number:
            return number.phone_number
        return None

and then in Django admin I have:

@admin.register(Merchant)
class MerchantAdmin(admin.ModelAdmin):
    list_display = ("name", "business_phone_number", ...)
    ...

I've put in get_queryset:

def get_queryset(self, request):
    return super().get_queryset(request).prefetch_related("phonenumber_set")...
    

CodePudding user response:

The hit in db made queryset.first(). For work with prefetched data you should use only prefetched_something.all(). in your case:

@property
def business_phone_number(self):
    for number in self.phonenumber_set.all():
        return number

or you can use next().

@property
def business_phone_number(self):
    return next((number for number in self.phonenumber_set.all()), None)

You can use self.phonenumber_set.all().iterator() instead of generator, but i have not use it with prefetch data.

  • Related