如何在DRF中序列化通用外键 [英] How to Serialize generic foreign key In DRF
本文介绍了如何在DRF中序列化通用外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有通用外键的模型,我想对该模型进行序列化。
I have model with generic foreign key and I want to serialize that model.
model.py
:
class AddressType(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type','object_id')
def __unicode__(self):
return u'%s' % str(self.content_type)
class AddressBook(TimeStampedModel):
class Meta:
db_table = 'address_book'
uuid = UUIDField(auto=True)
address_tag = models.CharField(null=True, blank=True, max_length=20)
# should be a generic foreign key
address_object_type = GenericRelation(AddressType)
address1 = models.CharField(
verbose_name='Address1',
max_length=200,
)
address2 = models.CharField(
verbose_name='Address2',
max_length=200,
)
serializer.py
:
class AddressBookSerializer(serializers.ModelSerializer):
class Meta:
model = AddressBook
fields = ('id','uuid','address_tag','address_object_type','address1','address2')
如何在上述模型上序列化JSON?
How can I serialize JSON on above model?
推荐答案
文档。
因此,如果要序列化 AddressType
,则需要实现以下类似内容:
So if you want to serialize AddressType
you will need to implement something like this:
class ContentObjectRelatedField(serializers.RelatedField):
"""
A custom field to use for the `content_object` generic relationship.
"""
def to_representation(self, value):
"""
Serialize tagged objects to a simple textual representation.
"""
if isinstance(value, Bookmark):
return 'Bookmark: ' + value.url
elif isinstance(value, Note):
return 'Note: ' + value.text
raise Exception('Unexpected type of tagged object')
其中书签
和 Note
是可能具有关联内容的对象。
Where Bookmark
and Note
are objects which may be have associated contents.
如果要序列化 AddressBook
,可以尝试执行以下操作:
If you want to serialize AddressBook
you can try doing something like this:
class AddressBookSerializer(serializers.ModelSerializer):
address_object_type = ContentObjectRelatedField()
class Meta:
model = AddressBook
fields = ('id','uuid','address_tag','address_object_type','address1','address2')
这篇关于如何在DRF中序列化通用外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文