Y
Y
Yshmeel2020-09-04 19:47:59
Django
Yshmeel, 2020-09-04 19:47:59

What to do if empty is returned in M2M field when using prefetch_related?

I'm using Django for my project's API, and I'm using Djongo to connect Django to MongoDB. In the end, due to the problem of n + 1 requests, I had to use prefetch_related. But, when I execute this function in the QuerySet, then the M2M fields that I prefetch become empty.

DRF test request:

DRF Test query  

@api_view(['GET'])
@permission_classes([AllowAny])
def test_prefetch(request):
    users = User.objects.prefetch_related('roles').filter(id=4) # id=4 - аккаунт с ролями
    print(users[0].roles.all())  # возвращает []
    print(users[0]._prefetched_objects_cache) # возвращает {"roles": []}
    return Response(123, status=200)

Models

class UserRoles(models.Model):     
    user = models.ForeignKey(to="User", on_delete=models.DO_NOTHING, default=None)    
    role_type = models.CharField(default="", max_length=256)    
    given_at = models.DateTimeField(default=api.functions.get_local_time)     
    expires_at = models.DateTimeField(default=api.functions.get_local_time, null=True) 
    def __str__(self): 
        return self.role_type  

class User(AbstractBaseUser, PermissionsMixin): 
    ....      
    roles = models.ManyToManyField(UserRoles, symmetrical=True)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question