Search code examples
pythondjangodjango-allauthprefetch

How to prefetch SocialAccount with django-allauth?


Django-allauth package creates a model SocialAccount, with a ForeignKey to User. I can't manage to prefetch this information in my queryset.

My model:

class Placerating(models.Model):
    author = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL)

Django-allauth model:

class SocialAccount(models.Model):
    user = models.ForeignKey(allauth.app_settings.USER_MODEL, on_delete=models.CASCADE)

When I try to prefetch this data:

rating = Placerating.objects.all().prefetch_related('author__socialaccount')

I get the following error message:

AttributeError: Cannot find 'socialaccount' on User object, 'author__socialaccount' is an invalid parameter to prefetch_related()

Any clue ? Thanks!


Solution

  • I got my answer.

    SocialAccount is a reverse Foreign key, so "_set" must be added at the end:

    rating = Placerating.objects.all().prefetch_related('author__socialaccount_set')