如何在Django中序列化GenericRelation [英] How to serialize a GenericRelation in django
问题描述
我正在使用django rest框架,我想序列化GenericRelation
.
在我的模型中,我有:
class Asset(model.Models):
name = models.CharField(max_length=40)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type','object_id')
class Project(models.Model):
name = models.CharField(max_length=40)
file = generic.GenericRelation(Asset)
我正在尝试为我的项目编写序列化,该序列化将返回名称和资产ID.我有这个:
class AssetObjectRelatedField(serializers.RelatedField):
def to_native(self, value):
if isinstance(value, Project):
serializer = Project(value)
else:
raise Exception('Unexpected type of asset object')
return serializer.data
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
file = AssetObjectRelatedField()
class Meta:
model = Project
fields = ('name','file')
当我尝试访问项目时,我得到:
意外的资产对象类型
有什么想法我想念的吗?
更新:我开始工作了.但这似乎不适合我阅读的文档.答案是将传递给AssetObjectRelatedField
的值视为资产类型.这与它的此处记录的方式不同.. >
我现在有以下可行的方法.
class AssetObjectRelatedField(serializers.RelatedField):
def to_native(self, value):
return value.id
将模型添加到内容类型可以解决此问题.这是一个示例.
content_object = generic.GenericForeignKey('content_type', 'object_id')
https://docs.djangoproject.com/en /dev/ref/contrib/contenttypes/#generic-relations
I am using django rest framework and I want to serialize a GenericRelation
.
In my models, I have:
class Asset(model.Models):
name = models.CharField(max_length=40)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type','object_id')
class Project(models.Model):
name = models.CharField(max_length=40)
file = generic.GenericRelation(Asset)
I'm trying to write a serialize for my project which will return name and asset id. I have this:
class AssetObjectRelatedField(serializers.RelatedField):
def to_native(self, value):
if isinstance(value, Project):
serializer = Project(value)
else:
raise Exception('Unexpected type of asset object')
return serializer.data
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
file = AssetObjectRelatedField()
class Meta:
model = Project
fields = ('name','file')
When I try to access projects, I get:
Unexpected type of asset object
Any ideas what I'm missing?
UPDATE: I got it working. But it doesn't seem to fit in with the documentation I have read. The answer is to treat the value passed to AssetObjectRelatedField
as an Asset type. This is different to how its documented here.
I now have the following which works.
class AssetObjectRelatedField(serializers.RelatedField):
def to_native(self, value):
return value.id
Adding your model to content type could fix this problem. Here is a example to do it.
content_object = generic.GenericForeignKey('content_type', 'object_id')
https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
这篇关于如何在Django中序列化GenericRelation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!