2016-08-02 70 views
3

我想了解如何在Django-Rest-Framework中使用GenericRelations。我找到了serializer relations的documetation頁面,並遵守了代碼。 我創建的模型:內TaggedItemSerializer在django-rest-framework中序列化一個通用關係

class BookmarkSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Bookmark 
     fields = ('url', 'link_url',) 


class NoteSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Note 
     fields = ('url', 'text',) 


class TaggedObjectRelatedField(serializers.RelatedField): 
    """ 
    A custom field to use for the 'tagged_object' generic relationship 
    """ 

    def to_representation(self, value): 
     """ 
     Serialize tagged objects to their respective serializer formats 
     :param value: 
     :return: 
      serializer.data 
     """ 
     if isinstance(value, Bookmark): 
      return 'Bookmark: ' + value.url 
     elif isinstance(value, Note): 
      return 'Note: ' + value.text 
     raise Exception('Unexpected type of tagged object') 


class TaggedItemSerializer(serializers.ModelSerializer): 
    tagged_object = TaggedObjectRelatedField() 
    class Meta: 
     model = TaggedItem 
     fields = ('url', 'id', 'tag_name', 'tagged_object') 

現在應該是什麼輸入TaggedObjectRelatedField()

class TaggedItem(models.Model): 
    """ 
    Tags arbitary model instance using a generic relation. 

    """ 
    tag_name = models.SlugField() 
    content_type = models.ForeignKey(ContentType) 
    object_id = models.PositiveIntegerField() 
    tagged_object = GenericForeignKey('content_type', 'object_id') 

    def __unicode__(self): 
     return self.tag_name 

class Bookmark(models.Model): 
    """ 
    A bookmark consists of a URL, and 0 or more descriptive tags. 
    """ 
    link_url = models.URLField() 
    tags = GenericRelation(TaggedItem) 

class Note(models.Model): 
    """ 
    A note consists of some texts, and 0 or more descriptive tags 
    """ 
    text = models.CharField(max_length=1000) 
    tags = GenericRelation(TaggedItem) 

我創建的序列化? 目前,我得到錯誤的

File "/home/aswin/Documents/WebProjects/drf_practice/uni_auth//loginpage/login/serializers.py", line 76, in TaggedItemSerializer 
    tagged_object = TaggedObjectRelatedField() 
    File "/home/aswin/Documents/WebProjects/drf_practice/uni_auth/lib/python3.5/site-packages/rest_framework/relations.py", line 80, in __init__ 
    'Relational field must provide a `queryset` argument, ' 
AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`. 

我試圖給參數作爲READ_ONLY =真太多,但它扔在同一error.just放什麼我究竟做了:

class TaggedItemSerializer(serializers.ModelSerializer): 
    tagged_object = TaggedObjectRelatedField(read_only=True) 

請幫助我與此

回答

2

我沒有看到您引用關於序列化TaggedItem的文章中的任何內容,爲什麼要序列化TaggedItem?

這裏是我的序列化器類:

from models import Bookmark, Note, TaggedItem 
from rest_framework import serializers 


class TaggedObjectRelatedField(serializers.RelatedField): 
    def to_representation(self, value): 
     if isinstance(value, Bookmark): 
      serializer = BookMarkSerializer(value) 
     elif isinstance(value, Note): 
      serializer = NoteSerializer(value) 
     else: 
      raise Exception('Unexpected type of tagged object') 

     return serializer.data 


class BookMarkSerializer(serializers.HyperlinkedModelSerializer): 
    tags = TaggedObjectRelatedField(many=True, queryset=TaggedItem.objects.all()) 

    class Meta: 
     model = Bookmark 
     fields = ('pk', 'url', 'tags') 


class NoteSerializer(serializers.HyperlinkedModelSerializer): 
    tags = TaggedObjectRelatedField(many=True, queryset=TaggedItem.objects.all()) 

    class Meta: 
     model = Note 
     fields = ('pk', 'text', 'tags') 
+0

這段代碼在DRF文檔肯定是錯過。會讓事情變得更清晰。 – cbo

+0

但爲什麼不應該'想要序列化TaggedItem'。我認爲這是對通用模型進行序列化的完全有效方法。這怎麼能做到? – cbo

相關問題