Including GenericForeignKey fields #942
Replies: 2 comments 4 replies
-
This is achievable by using PolymorphicResourceRelatedField, with an abstract class being the base class (this fails in schema generation in DRF side as abstract classes shouldn't be used in |
Beta Was this translation helpful? Give feedback.
-
In the example app there is an example which uses the reverse relationship using Like the following: class TaggedItem(BaseModel):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
def __str__(self):
return self.tag
class Meta:
ordering = ("id",)
class Blog(BaseModel):
name = models.CharField(max_length=100)
tagline = models.TextField()
tags = GenericRelation(TaggedItem)
def __str__(self):
return self.name
class Meta:
ordering = ("id",)
class TaggedItemSerializer(serializers.ModelSerializer):
class Meta:
model = TaggedItem
fields = ("tag",)
class BlogSerializer(serializers.ModelSerializer):
copyright = serializers.SerializerMethodField()
tags = relations.ResourceRelatedField(many=True, read_only=True)
included_serializers = {
"tags": "example.serializers.TaggedItemSerializer",
}
def get_copyright(self, resource):
return datetime.now().year
def get_root_meta(self, resource, many):
return {"api_docs": "/docs/api/blogs"}
class Meta:
model = Blog
fields = ("name", "url", "tags")
read_only_fields = ("tags",)
meta_fields = ("copyright",) To directly serialize |
Beta Was this translation helpful? Give feedback.
-
When you have a model defined as:
And a serializer defined as:
How to use the include "feature" for generic foreign keys?
There is this #319 but it doesn't seem right...
Beta Was this translation helpful? Give feedback.
All reactions