Serializer不会返回新创建的相关对象

时间:2015-12-24 17:06:04

标签: django django-rest-framework

在POST请求中,我创建了Item的实例,然后将其添加到FoodItem创建中。 从帖子请求中返回我return Response(serializer.data) 但是,FoodItem部分是空的。 如果我在这个新项目上调用GET请求,我会获得FoodItem数据。 我可以在创建FoodItem对象后刷新序列化程序吗?

class Item(models.Model):
        ITEMTYPE = (
            (1, 'Food'),
            (2, 'Clothes'),
            (3, 'Electronic')
        )
        itemType = models.IntegerField(choices=ITEMTYPE)
        description = models.CharField(max_length=255,blank=True)
        date_created = models.DateTimeField(auto_now_add=True)
        date_modified = models.DateTimeField(auto_now=True, null=True)
        date_deleted = models.DateTimeField(blank=True, null=True)
        price = models.IntegerField()

class FoodItem(models.Model):
        item = models.OneToOneField(Item, blank=True)
        foodType = models.CharField(max_length=255,blank=True)
        calories = models.IntegerField()

我的创建代码

def create(self, request, user_pk=None):
    data = request.data

    serializer = ItemSerializer(data=data)
    serializer.is_valid()
    serializer.save()

    data['item'] = serializer.data['id']
    serializer2 = FoodItemSerializer(data=data)
    serializer2.is_valid()
    serializer2.save()

    return Response(serializer.data)

编辑:序列化程序

class FoodItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = FoodItem
        fields = ('id','item','foodType','calories')

class ItemSerializer(serializers.ModelSerializer):
    itemType_display = serializers.ReadOnlyField(source='get_itemType_display')
    foodItem = FoodItemSerializer(many=False, read_only=True)

    class Meta:
        model = Post
        fields = ('id','itemType','itemType_display','description','date_created','date_modified','price','foodItem')
        read_only_fields = ['foodItem']

0 个答案:

没有答案