I have a user model and a profile model that is created automatically when a user is registered. In my view for retrieving the user profile, I am trying to get the user profile using the username
but DRF uses pk
by default. So I added a lookup field with the username
but DRF can't seem to resolve it:
my profile
model:
class Profile(TimeStampedModel):
user = models.OneToOneField('User', on_delete=models.CASCADE, related_name='customer_profile')
bio = models.TextField(blank=True)
image = models.URLField(blank=True)
def __str__(self):
return self.user.username
my profile serializer
:
class ProfileSerializer(serializers.ModelSerializer):
username = serializers.StringRelatedField(source='user.username', read_only=True)
bio = serializers.CharField(allow_blank=True, allow_null=True)
image = serializers.SerializerMethodField()
class Meta:
model = Profile
fields = ['username', 'bio', 'image']
def get_image(self, obj):
if obj.image:
return obj.image
return 'https://static.productionready.io/images/smiley-cyrus.jpg'
my profile retrieving view
:
class ProfileRetrieveAPIView(generics.RetrieveAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
lookup_field = 'username'
def retrive(self, request, username, *args, **kwargs):
try:
profile = Profile.objects.select_related('user').get(
user__username = username
)
except Profile.DoesNotExist:
ProfileDoesNotExist
serializer = self.serializer_class(profile)
return Response(serializer.data, status=status.HTTP_200_OK)
my profile endpoint:
urlpatterns = [
# ....
path('profiles/<str:username>', views.ProfileRetrieveAPIView.as_view()),
]
I am getting the error:
Cannot resolve keyword 'username' into field. Choices are: bio, created_at, id, image, updated_at, user, user_id
What am I doing wrong?
Use nested serialzer.
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username',)
And in your profile serializer:
username = UserSerializer(many=False, read_only=True)
You can use this
class ProfileSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username', read_only=True)
bio = serializers.CharField(allow_blank=True, allow_null=True)
image = serializers.SerializerMethodField()
class Meta:
model = Profile
fields = ['username', 'bio', 'image']
def get_image(self, obj):
if obj.image:
return obj.image
return 'https://static.productionready.io/images/smiley-cyrus.jpg'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.