3

这是我的模型:

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 的新手,我只是不知道为什么会得到这个......

如果你看到一些明显的东西,我会很高兴知道它!

4

1 回答 1

3

在使用不需要的模型时摆脱 restore_object 。请改用modelSerializer

class AddressSerializer(serializers.ModelSerializer):

    class Meta:
        model = Address
        fields = ('id', 'address_complete', 'door_code')
于 2013-02-24T22:19:34.490 回答