[Answered ]-Groupby using Django's ORM to get a dictionary of lists between two models

1👍

There is no need to do this, you can query with:

users = User.objects.prefetch_related('users')

For a user you can then:

for user in users:
    for gift in user.users.all():
        print(user, ' -> ', gift)

The reason you access these through .users is because of the related_name=.. parameter [Django-doc], which also shows why this is not a good name. You can use:

from django.conf import settings


class User(models.Model):
    name = models.CharField(max_length=150, null=True, blank=True)
    # …


class Gift(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='gifts',
        on_delete=models.CASCADE,
    )
    # …

Then you access these with:

users = User.objects.prefetch_related('gifts')
for user in users:
    for gift in user.gifts.all():
        print(user, ' -> ', gift)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment