DEV Community

sium_hossain
sium_hossain

Posted on

7 3

How to save model object using only foreign keys id in django-rest-framework

If you want save some data like me in a model which has foreign key field and want to save only by id in foreign key field. Then this method is for you 🐎

models.py
Here is the foreign key field where I want to save this object just passing foreign key id.
model

In serializers.py we have to put serializers.PrimaryKeyRelatedField on foreign key field name like this -



unit = serializers.PrimaryKeyRelatedField(queryset= Unit.objects.all(),many=False)


Enter fullscreen mode Exit fullscreen mode

serializers

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs