我是Django休息和序列化概念的新手
我有这种数据库结构
用户1-> N地址, 用户1-> N电话
User
是一个django.contrib.auth.models.User。 Address
和Phone
两个模型都包含此字段user_id = models.ForeignKey(User, on_delete=models.CASCADE)
在我的UserSerializer中看起来像这样
class UserSerializer(serializers.ModelSerializer):
address = AddressSerializer(many=False)
phone = PhoneSerializer(many=False)
class Meta:
model = User
fields = (
'id', 'username',
'first_name', 'last_name',
'email', 'password',
'address', 'phone')
def create(self, validated_data):
# Save user.
user = User.objects.create(
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
username=validated_data['username'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.save()
# User's address
address_data = validated_data['address']
address_data['user_id'] = user.id
address = Address.objects.create(**address_data)
# User's phone
phone_data = validated_data['phone']
phone_data['user_id'] = user.id
phone = Phone.objects.create(**phone_data)
return user
和AddressSerializer:
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = (
'user_id', 'address', 'pin_code', 'state', 'city', 'country')
我可以创建User
,但在执行serializer.data
时我收到此错误:
AttributeError: Got AttributeError when attempting to get a value for field `address` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'address'.
编辑:
我的create
方法看起来像这样
def create(self, validated_data):
password = validated_data.pop('password')
validated_data['username'] = validated_data['email']
user = User.objects.create(**validated_data)
user.set_password(password)
user.save()
return user
答案 0 :(得分:1)
如果您未明确指定address_set
,则应拨打地址和电话字段phone_set
和related_name
class UserSerializer(serializers.ModelSerializer):
address_set = AddressSerializer(many=False)
phone_set = PhoneSerializer(many=False)
class Meta:
model = User
fields = (
'id', 'username',
'first_name', 'last_name',
'email', 'password',
'address_set', 'phone_set'
)
或
class UserSerializer(serializers.ModelSerializer):
address = AddressSerializer(many=False, source='address_set')
phone = PhoneSerializer(many=False, source='phone_set')
class Meta:
model = User
fields = (
'id', 'username',
'first_name', 'last_name',
'email', 'password',
'address', 'phone'
)