我正在构建如下的活动模型。它具有content_type作为目标。
class Activity(models.Model):
user = models.ForeignKey(Auth, related_name='activity')
content_type = models.ForeignKey(ContentType, null=True)
object_id = models.PositiveIntegerField()
doc_object = GenericForeignKey('content_type', 'object_id')
现在,我们已经创建了一些模型,可以在Activity模型中使用这种模型。
class Comment(models.Model):
user = models.ForeignKey(Auth, related_name='comment')
title = models.CharField(max_length=256)
class Question(models.Model):
user = models.ForeignKey(Auth, related_name='question')
title = models.CharField(max_length=256)
answer = models.TextField()
class Like(models.Model):
user = models.ForeignKey(Auth, related_name='like')
status = models.BooleanField(default=False)
我写了如下的序列化器
class AtivityInstanceRelatedField(serializers.RelatedField):
"""
A custom field to use for the `tagged_object` generic relationship.
"""
def to_representation(self, value):
"""
Serialize tagged objects to a simple textual representation.
"""
if isinstance(value, Comment):
return 'Comment: ' + value.title
elif isinstance(value, Question):
return 'Question: ' + value.title
if isinstance(value, Like):
return 'Like: ' + Like.status
raise Exception('Unexpected type of tagged object')
class AtivitySerializer(serializers.ModelSerializer):
content_type = DocTemplateInstanceRelatedField(read_only=True)
class Meta:
model = Ativity
fields = ['user','content_type']
我们方面的输出是从模型中获取字段名称 例如。
{
content_type:{
Comment:{
id,
user,
title,
},
Question:{
id,
user,
title,
answer,
},
Like:{
id,
user,
status,
}
}
}
如何将数据发布到相关模型中。 寻找急需的帮助,谢谢。