如何在前端将PrimaryKeyRelatedField表示为字段名?目前正在获得ValueError

时间:2015-11-18 00:56:39

标签: django django-rest-framework

这是我的模特:

class Location(models.Model):
    alphaNumNoSpaces = RegexValidator(r'^[a-zA-Z0-9]+$', 'Only letters and numbers are allowed. There should no spaces.')
    alphaSpaces = RegexValidator(r'^[a-zA-Z ]+$', 'Only letters and spaces are allowed.')

    locationName = models.CharField(max_length=80, unique=True, validators=[alphaSpaces])
    locationCode = models.CharField(max_length=10, unique=True, validators=[alphaNumNoSpaces])

class UserExtended(models.Model):
    user = models.OneToOneField(User)
    location = models.ForeignKey(Location)

我使用的是默认的Django User模型。这是我的UserSerializer:

class UserSerializer(serializers.ModelSerializer):
    # Used source because I want the front-end to receive the location name
    # and not the pk value.
    location = serializers.PrimaryKeyRelatedField(source='userextended.location.locationName', queryset=Location.objects.all())

    class Meta:
        model = User
        fields = ('username', 'password', 'email', 'location',)
        read_only_field = ('location')

    def create(self, validated_data):
        user = User.objects.create_user(
            email = validated_data['email'],
            username = validated_data['username'],
            password = validated_data['password'],
        )
        print(validated_data['userextended']['location'])
        UserExtended.objects.create(user=user, location=validated_data['userextended']['location'])
        return user

问题是,当我将这些数据发送到后端以创建User对象时:

Location.objects.create(locationName = 'My Location', locationCode = 'ML')

data = {'username': 'a', 'password': 'a', 'email': 'a@hotmail.com', 'location': '1'}

我收到错误说:

ValueError: Cannot assign "{'locationName': <Location: Location object>}": "UserExtended.location" must be a "Location" instance.

并且此错误追溯到此行:

UserExtended.objects.create(user=user, location=validated_data['userextended']['location'])

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您正在寻找SlugRelatedfield而不是PrimaryKeyRelatedField,因为locationName不是Location主键。