我正在尝试发布默认值。
用简单的英语,这就是我希望它工作的方式:
我的帖子数据不在发布的JSON数据中包含字段tag
。
当没有tag
字段
当没有标记字段时,它告诉我'标记字段是必需的'
{title: "Testing"}
class Tag(models.Model):
name = models.CharField("Name", max_length=5000, blank=True)
taglevel = models.IntegerField("Tag level", null=True, blank=True)
owner = models.ForeignKey('auth.User', blank=True, null=True)v
class Item(models.Model):
title = models.CharField("Title", max_length=10000, blank=True)
tag = models.ManyToManyField('Tag', blank=True)
owner = models.ForeignKey('auth.User', blank=True, null=True)
class ItemSerializer(serializers.ModelSerializer):
tag = TagSerializer(many=True, read_only=False)
info = InfoSerializer(many=True, read_only=True)
class Meta:
model = Item
ordering = ('-created',)
fields = ('title', 'pk', 'tag')
def create(self, validated_data):
tags_data = validated_data.pop('tag')
owner = self.context['request'].user
item = Item.objects.create(owner=owner, **validated_data)
for tag_data in tags_data:
tag_data['owner'] = owner
tag_qs = Tag.objects.filter(name__iexact=tag_data['name'])
if not tag_data:
Tag.objects.get_or_create(tag_name="None")
if tag_qs.exists():
tag = tag_qs.first()
else:
tag = Tag.objects.create(**tag_data)
item.tag.add(tag)
return item
答案 0 :(得分:0)
尝试在ItemSerializer的代码字段中设置default=None
。
您的ItemSerializer现在应该是:
class ItemSerializer(serializers.ModelSerializer):
tag = TagSerializer(default=None, many=True, read_only=False)
info = InfoSerializer(many=True, read_only=True)
...