gpt4 book ai didi

python - Rest框架如何创建可选的嵌套对象?

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:44 25 4
gpt4 key购买 nike

DRF 3.1.3、Django 1.8.3

我有几个模型,就像下面的代码:

Post

class Post(models.Model):
class Meta:
ordering = ['-updated_time']

author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+')
circle = models.ForeignKey('circle')

TYPE_CHOICES = (
('M', _('Members')),
('O', _('Org')),
)
type = models.CharField(_('Type'), choices=TYPE_CHOICES, default='M', max_length=1, help_text=u"帖子类型,是成员发帖,还是组织发帖?")

created_time = models.DateTimeField(auto_now_add=True, db_index=True, editable=False)
updated_time = models.DateTimeField(auto_now=True, db_index=True, editable=False)

like = models.PositiveIntegerField(default=0)

comments = GenericRelation(PostComment)
images = GenericRelation(PostImage)
likes = GenericRelation(PostLike)

is_removed = models.BooleanField(_('Is Removed'), default=False, db_index=True)

RichPost

class RichPost(models.Model):
title = models.CharField(max_length=100)
summary = models.TextField(max_length=560)
content = models.TextField(max_length=16000)

post = models.OneToOneField(Post, related_name='rich')

SimplePost

class SimplePost(models.Model):
content = models.TextField(max_length=560)
post = models.OneToOneField(Post, related_name='simple')

PostSerializer

class PostSerializer(serializers.ModelSerializer):
images = PostImageSerializer(many=True)

simple = SimplePostSerializer(many=False)
rich = RichPostSerializer(many=False)

is_liked = serializers.SerializerMethodField('is_liked_by_user')

def create(self, validated_data):
simple = validated_data.pop('simple')
rich = validated_data.pop('rich')
post = Post.objects.create(**validated_data)
return post

def is_liked_by_user(self, obj):
request = self.context['request']
obj_type = ContentType.objects.get_for_model(obj)
if PostLike.objects.filter(author=request.user, content_type__pk=obj_type.id, object_id=obj.id).exists():
return True
else:
return False

class Meta:
model = Post
fields = ('id', 'author', 'circle', 'type', 'created_time', 'updated_time', 'like', 'is_removed',
'images', 'comments_count', 'is_liked', 'simple', 'rich')
read_only_fields = ('comments_count', 'is_liked', 'created_time', 'updated_time', 'like', 'author')

Post 属于 RichPost 和 SimplePost 之一。

当我创建帖子时,两者都是必需的。

例如,当我发送 simple.content 时,需要 rich.title、rich.summary、rich.content。

然后,我找到了api文档:writable-nested-representations

我重写了.create()方法

但它根本没有被调用,在尝试访问经过验证的数据或保存对象实例之前,is_valid()

有人有想法吗?谢谢您的回答。

最佳答案

序列化器中需要丰富和简单的帖子。您应该将它们设为可选。如果您至少需要其中一个,您可以在 validate() 中执行此操作:

class PostSerializer(serializers.ModelSerializer):
simple = SimplePostSerializer(required=False)
rich = RichPostSerializer(required=False)
...
def validate(self, data):
data = super(PostSerializer, self).validate(data)
if not any([data.get('simple'), data.get('rich')]):
raise serializers.ValidationError('Either simple or rich is required')
return data

关于python - Rest框架如何创建可选的嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com