Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Including GenericForeignKey fields#942

SafaAlfulaij started this conversation inGeneral
Discussion options

When you have a model defined as:

classTaggedItem(models.Model):tag=models.SlugField()content_type=models.ForeignKey(ContentType,on_delete=models.CASCADE)object_id=models.PositiveIntegerField()content_object=GenericForeignKey('content_type','object_id')

And a serializer defined as:

classTaggedItemSerializer(serializers.ModelSerializer):content_object=relations.ResourceRelatedField(read_only=True)# This returns correct results based on the object (proper `id`s and `type`s)included_serializers= {"content_object":"",# What to have here?    }classMeta:model=TaggedItemfields= ("tag","content_object")

How to use the include "feature" for generic foreign keys?
There is this#319 but it doesn't seem right...

You must be logged in to vote

Replies: 2 comments 4 replies

Comment options

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 inModelSerializers, but solvable).
The missing part is input and validation. This will require some changes to allow validating type (if not there) and queryset.

You must be logged in to vote
2 replies
@sliverc
Comment options

I've found a related discussion onJSON:API forums which discusses polymorphic relationships and its challenges.

Especially when it comes toinclude parameter JSON:API assumes an uniform API to work. So actually also a reason whyGenericForeignKey is not supported.

@SafaAlfulaij
Comment options

As mentioned,PolymorphicResourceRelatedField already have this kind of functionality, so it worked for me. And I solved the input part by modifyingto_internal_value ofrelations.PolymorphicResourceRelatedField to interpolate the type.
Even if JSON:API doesn't really know how to do it, as long as the solution provided here is solid, it's enough.
One problem of this is that related includes can't work easily.

Comment options

In the example app there is an example which uses the reverse relationship usingGenericRelation, where include works.

Like the following:

classTaggedItem(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):returnself.tagclassMeta:ordering= ("id",)classBlog(BaseModel):name=models.CharField(max_length=100)tagline=models.TextField()tags=GenericRelation(TaggedItem)def__str__(self):returnself.nameclassMeta:ordering= ("id",)classTaggedItemSerializer(serializers.ModelSerializer):classMeta:model=TaggedItemfields= ("tag",)classBlogSerializer(serializers.ModelSerializer):copyright=serializers.SerializerMethodField()tags=relations.ResourceRelatedField(many=True,read_only=True)included_serializers= {"tags":"example.serializers.TaggedItemSerializer",    }defget_copyright(self,resource):returndatetime.now().yeardefget_root_meta(self,resource,many):return {"api_docs":"/docs/api/blogs"}classMeta:model=Blogfields= ("name","url","tags")read_only_fields= ("tags",)meta_fields= ("copyright",)

To directly serializeGenericForeignKeyDRF docs suggest to create custom related field which overwritesto_representation. This won't help in our case though asincluded_serializers is a separate DJA feature. As far as I see are theinclude feature can only be used withGenericRelation but currently not withGenericForeignKey directly. For this to work I assume there needs to be an API change where included serializers is directly configured onResourceRelatedField which can then be overwritten.

You must be logged in to vote
2 replies
@auvipy
Comment options

as far as I can remember, django core devs suggest not to use genericforeignkey

@SafaAlfulaij
Comment options

Can you please share the source? It's not the best, I know, but sometimes it's a must...

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
General
Labels
None yet
3 participants
@SafaAlfulaij@sliverc@auvipy

[8]ページ先頭

©2009-2025 Movatter.jp