முக்கிய பிரச்சனை என்னவென்றால், வெளிநாட்டு விசைக்கு தரவை அனுப்ப நீங்கள் POST முறையைப் பயன்படுத்த வேண்டும்.
I have a model with a foreign key. I am trying to post data to this model using the Django Rest Framework. How do I post data to the foreign key? <code>class Model1(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Model2(models.Model): name = models.CharField(max_length=100) model1 = models.ForeignKey('Model1', on_delete=models.CASCADE, related_name='model2') def __str__(self): return self.name class Model2Serializer(serializers.ModelSerializer): class Meta: # noqa: D106,D205,D400,E501 # pylint: disable=too-few-public-methods,missing-docstring,line-too-long,no-init # noqa: D105 # pylint: disable=R0903 # noqa: D102 # pylint: disable=R0901 model = Model2 fields = ['id', 'name', 'model1'] </code>
இந்த குறியீடு இரண்டு மாதிரிகளை வரையறுக்கிறது, Model1
மற்றும் Model2
, மற்றும் ஒரு சீரியலைசர் Model2
.
Model1
என்று ஒரு துறை உள்ளது name
.
Model2
என்று ஒரு துறை உள்ளது name
, மற்றும் வெளிநாட்டு முக்கிய புலம் என்று அழைக்கப்படும் model1
. வெளிநாட்டு முக்கிய இணைப்புகள் Model1
.
க்கான சீரியலைசர் Model2Serializer
, மாதிரியை JSON வடிவத்திற்கு மாற்றும் போது எந்த புலங்கள் சேர்க்கப்பட வேண்டும் என்பதை வரையறுக்கிறது. இந்த வழக்கில், இது புலங்களை உள்ளடக்கியது: id
, name, and 'model1'.
Save Foreign Key Using Django Rest Framework
In Django, you can use the save_foreign_key() function to save a foreign key in a model. This function takes two arguments: the model name and the name of the column in the model that stores the foreign key.
To save a foreign key in a model named "MyModel", you would use the following code:
save_foreign_key("MyModel", "id")
What is Foreign key
A foreign key is a column in a table that references a column in another table. When you insert data into the table, Django automatically creates the foreign key for you.