I am trying to learn how to use GenericRelations in Django-Rest-Framework.
I found the documetation page for serializer relations
<http://www.django-rest-framework.org/api-guide/relations/#the-queryset-argument>
and
followed the codes. I created the models:
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)
I created the serializers:
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')
Now what should be the input to the *TaggedObjectRelatedField()* inside
*TaggedItemSerializer*? Currently I am getting error as
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`.
I tried giving the arguments as *read_only=True* too but it threw the same
error.just to put what i exactly did:
class TaggedItemSerializer(serializers.ModelSerializer): tagged_object =
TaggedObjectRelatedField(read_only=True)
Please help me with this. I am using django 1.9 and drf 3.4
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.