Can anybody explain me why am in getting this error.
I have two models User and Profile with OnetoOne relations. models.py
class User(AbstractBaseUser):
phone_number = models.IntegerField(unique=True, verbose_name='phone number')
email = models.EmailField()
class Profile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,)
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
and here's the serializer.py
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields =["first_name", "last_name"]
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = User
fields = ["id", "phone_number", "email", "profile",]
Views.py
class UserDetailsView(generics.RetrieveUpdateAPIView):
serializer_class = UserSerializer
def get_queryset(self):
return User.objects.filter(pk=self.kwargs['pk'])
CodePudding user response:
You write the serializer in wrong way. The profile model has user column & user table doesn't have profile column and one thing Use OneToOne filed when creating a profile model against a user. Because one profile can contain one user.
models.py
class User(AbstractBaseUser):
phone_number = models.IntegerField(unique=True, verbose_name='phone
number')
email = models.EmailField()
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "phone_number", "email"]
class ProfileSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Profile
fields =["first_name", "last_name", "user"]
for more information about nested serializer please follow the official documentation