3

Here is my model:

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"

I created a serializer for this in 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)

When I try to serialize an address using python manage?py shell, here is what I got:

>>> seria = AddressSerializer(Address)
>>> seria.data
AttributeError: type object 'Address' has no attribute 'address_complete'

Being new to DjangoRestFramework, I just don't know why I got this...

If you see something obvious, I would be glad to know it!!

1 Answer 1

3

Get rid of restore_object as you are using a Model it's not needed. Use the modelSerializer instead.

class AddressSerializer(serializers.ModelSerializer):

    class Meta:
        model = Address
        fields = ('id', 'address_complete', 'door_code')
Sign up to request clarification or add additional context in comments.

4 Comments

I tried modelSerialiser but this time I have "AttributeError: type object 'Address' has no attribute 'id'"
are you missing ID? see above
Well you help me a lot. You solution is working. But m y true error was quite a 'noob' one: i did a seria = AddressSerializer(Address) instead of a seria = AddressSerializer(address) (basically I was trying to serialize the model and not an object from the model...)
glad it helped easy mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.