Search code examples
pythondjangodjango-rest-frameworkdjongo

Empty M2M data if using prefetch_related django


i'm using Django with DRF, and i stucked on a N+1 problem. So, i trying to use prefetch_related now, and i have some problems with it. prefetch_related returns empty queryset in any situation.

I'm using:

  1. Django 3.0.7
  2. Djongo (Django DB Backend for MongoDB)
  3. DRF (latest version)

I tried to switch my project on MySQL, but it didn't helped

DRF Test query  

@api_view(['GET'])
@permission_classes([AllowAny])
def test_prefetch(request):
    users = User.objects.prefetch_related('roles').filter(id=4) # id=4 it's my account which has roles
    print(users[0].roles.all())  # returns []
    print(users[0]._prefetched_objects_cache) # returns {"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)

Solution

  • Fixed. Problem was in Djongo. I switched my project on PostgreSQL and it works now.