问题描述:

New to django so bare with me here - I am trying to deserialize and save an object from some JSON.

I've got a couple object that looks like this:

class Item(models.Model):

created_at = models.DateTimeField(default=utcnow)

category = models.ForeignKey(Category, related_name='items')

class Category(models.Model):

name = models.CharField(max_length=140, unique=True)

description = models.TextField(default='', blank=True)

created_at = models.DateTimeField(default=utcnow)

Now, I define serializers for these objects like this:

class CategorySerializer(serializers.ModelSerializer):

class Meta:

model = EventCategory

fields = (

'id',

'name',

'description'

)

class ItemSerializer(serializers.ModelSerializer):

created_at = serializers.DateTimeField()

category = CategorySerializer()

class Meta:

model = Event

fields = (

'id',

'created_at',

'category',

)

What is a little funky about this data structuring is that the 'Category' objects need not be altered, and I don't want to create any new ones - I've pre-defined a bunch of these objects and they essentially express the 'type' of item we are dealing with. We won't be saving, updating, or adding new ones.

OK, now lets say I have a JSON representation of an Item that looks like this:

{'category': {'id': 1, 'name': 'some_name', 'description': 'some_description}, 'id': 101, 'created_at': date_info}

I would like create and save the Item object, but do not want to create a new category object. If I do this:

serializer = ItemSerializer(data=data)

if serializer.is_valid():

serializer.save()

It complains that I am violating the unique=True constraint on the category's name field. I am assuming that the serializer is propagating the save operation to the category as well. My question: how can I define my serializers so that I can read out the category JSON when serializing, but so that I do not get this error when I am deserializing?

Thanks!!

网友答案:

You can have two serializers, one for each operation. Then, on your viewset, add a function that properly selects between them:

class StuffReadSerializer (...)
class StuffWriteSerializer (...)

class StuffViewSet(viewsets.ModelViewSet):
    model = Stuff

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return StuffReadSerializer
        return StuffWriteSerializer
相关阅读:
Top