Django用户自定义模型中缺少字段

时间:2016-11-16 22:22:41

标签: python django django-rest-framework

在Django REST中尝试使用经典序列化程序后,我目前正在尝试使用自定义模型,即我的模型有一个OneToOneField字段。

我的模型(在models.py中)是自定义User

class Friend2(models.Model):
    user = models.OneToOneField(User)
    add_field = models.CharField(max_length=15)

我将它(在serializers.py中)序列化(基于this SO topic):

class Friend2Serializer(serializers.HyperlinkedModelSerializer):

    add_field = serializers.CharField(source='friend2.add_field')

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'email', 'add_field')

    def create(self, validated_data):
        profile_data = validated_data.pop('friend2', None)
        user = super(Friend2Serializer, self).create(validated_data)
        self.create_or_update_user(user, profile_data)
        return user

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('friend2', None)
        self.create_or_update_profile(instance, profile_data)
        return super(Friend2Serializer, self).update(instance, validated_data)

    def create_or_update_user(self, user, profile_data):
        profile, created = Friend2.objects.get_or_create(user=user, defaults=profile_data)
        if not created and profile_data is not None:
            super(Friend2Serializer, self).update(profile, profile_data)

要POST数据以注册新用户,我使用以下代码片段:

import requests
import json

json_data = {'username': 'mylogin12', 'password': 'mypassword', 'email': 'mymail12@wanadoo.fr', 'add_field' : 'myaddfield'}
r = requests.post('http://127.0.0.1:8000/register_new_user', json=json_data)

在我的views.py

@api_view(['POST'])
def register_new_user(request):

    if request.method == 'POST':
        print('POST request !')

        print(request.data)
        serializer = Friend2Serializer(data=request.data)

        if serializer.is_valid():

            serializer.save()
            print('save friend!')
            return HttpResponse(status.HTTP_201_CREATED)

        else:
            print(serializer.errors)
            return HttpResponse(status.HTTP_403_FORBIDDEN)

到目前为止,它有效。

但是,当我尝试使用以下命令检索所有注册用户时

def get_all_users(request):

    all_friends = Friend2.objects.all()

    serial = Friend2Serializer(all_friends, many=True)
    json_data = JSONRenderer().render(serial.data)

    return HttpResponse(json_data, content_type='application/json')

我收到以下错误:

Got AttributeError when attempting to get a value for field `username` on serializer `Friend2Serializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Friend2` instance.
Original exception text was: 'Friend2' object has no attribute 'username'.

但我不明白为什么username字段不存在它是User模型的属性。

修改

我试图根据以下内容修改序列化程序:

class Friend2Serializer(serializers.ModelSerializer):

username = serializers.CharField(source='user.username')
password = serializers.CharField(source='user.password')
email = serializers.CharField(source='user.email')
add_field = serializers.CharField(allow_blank=True)

class Meta:
    model = Friend2
    fields = ('username', 'password', 'email', 'add_field')
    depth = 1

def create(self, validated_data):
    profile_data = validated_data.pop('friend2', None)
    user = super(Friend2Serializer, self).create(validated_data)
    self.create_or_update_user(user, profile_data)
    return user

def update(self, instance, validated_data):
    profile_data = validated_data.pop('friend2', None)
    self.create_or_update_profile(instance, profile_data)
    return super(Friend2Serializer, self).update(instance, validated_data)

def create_or_update_user(self, user, profile_data):
    profile, created = Friend2.objects.get_or_create(user=user, defaults=profile_data)
    if not created and profile_data is not None:
        super(Friend2Serializer, self).update(profile, profile_data)

但是现在,我收到以下错误:

raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])

TypeError:'用户'是此函数的无效关键字参数

1 个答案:

答案 0 :(得分:0)

Friend2模型有一个user字段,而不是username。将[{1}}替换为序列化程序类中的username