मुख्य समस्या यह है कि आपको विदेशी कुंजी पर डेटा भेजने के लिए 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.