这是我的模特:
class Address(models.Model):
"""
This is an Adress
"""
address_complete = models.CharField(max_length=100)
door_code = models.CharField(max_length=20, blank=True, null=True)
floor = models.IntegerField(blank=True, null=True)
infos = models.CharField(max_length=100, blank=True, null=True)
class Meta:
verbose_name_plural = "Addresses"
我在serializer.py中创建了一个序列化器:
from rest_framework import serializers
from party_app.models import Address, UserProfile, Stuff, Event, Bringing, Quantity
class AddressSerializer(serializers.Serializer):
pk = serializers.Field()
address_complete = serializers.CharField(max_length=100)
door_code = serializers.CharField(max_length=20)
floor = serializers.IntegerField()
infos = serializers.CharField(max_length=100)
def restore_object(self, attrs, instance=None):
"""
Create or update a new UserProfile instance.
"""
if instance:
# Update existing instance
instance.address_complete = attrs.get('address_complete', instance.address_complete)
instance.door_code = attrs.get('door_code', instance.door_code)
instance.floor = attrs.get('floor', instance.floor)
instance.infos = attrs.get('infos', instance.infos)
return instance
# Create new instance
return Address(**attrs)
当我尝试使用python manage?py shell序列化地址时,我得到的是:
>>> seria = AddressSerializer(Address)
>>> seria.data
AttributeError: type object 'Address' has no attribute 'address_complete'
刚接触DjangoRestFramework时,我只是不知道为什么会这样......
如果你看到明显的东西,我会很高兴知道它!
答案 0 :(得分:3)
在使用不需要的模型时,摆脱restore_object。请改用modelSerializer。
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = ('id', 'address_complete', 'door_code')