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:
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)
Fixed. Problem was in Djongo. I switched my project on PostgreSQL and it works now.