I'm having trouble understanding how the Django Rest Framework handles related model instances, when it is serializing data.
For example, I have two models that are both related to the django `User':
from django.contrib.auth.models import User
from django.db import models
class UserStatus(models.Model):
user = models.ForeignKey(User)
created = CreationDateTimeField()
def is_anonymous(self):
return self.user.userprofile.anonymous_user
class UserProfile(models.Model):
user = models.OneToOneField(User)
anonymous_user = models.BooleanField(default=False)
If I serialize a model instance using the following approach, it works fine:
from rest_framework import serializers
class UserStatusSerializer(serializers.ModelSerializer):
get_anonymous = serializers.SerializerMethodField('get_anonymous_state')
def get_anonymous_state(self, obj):
return self.object.user.userprofile.anonymous_user
class Meta:
model = UserStatus
fields = ('id', 'get_anonymous',)
My view to call the serializer is structured like this:
def put(self, request, *args, **kwargs):
user = self.request.user
serializer = UserStatusSerializer(self.model.objects.filter(user=user, data=request.DATA)
if serializer.is_valid():
new_serializer = UserStatusSerializer(user)
return Response(new_serializer.data, status=status.HTTP_200_OK)
If I try to use a method, that exists on the model UserStatus, I get an error:
class UserStatusSerializer(serializers.ModelSerializer):
is_anonymous = serializers.Field(source='is_anonymous')
class Meta:
model = UserStatus
fields = ('id', 'is_anonymous',)
In the second approach, I get the error message:
Exception Value: UserStatus has no user
I really don't understand what is going on. If I set a trace and step through the PUT request line by line, it works fine and the correct relationships exist (for example, I am in the method, I can access self.user.userprofile.anonymous_user); it steps through the serialization twice and it breaks the second time. It also does not work when I let I test it out as a complete code-block. Any suggestions on what I am doing wrong?