I am learning DRF.
So I have 2 models, Teams and Competitions.
This are my models:
class Team(models.Model):
"""Model representing Team object"""
club = models.ForeignKey(
Club,
on_delete=models.CASCADE,
related_name="teams",
null=True,
blank=True
)
name = models.CharField(
max_length=200,
help_text="Team name",
verbose_name="Team name"
)
deputy = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True,
)
competition = models.ForeignKey(
Competition,
on_delete=models.CASCADE
)
last_updated = models.DateTimeField(
auto_now=timezone.now
)
class Competition(models.Model):
name = models.CharField(
max_length=254,
null=False,
blank=False
)
last_updated = models.DateTimeField(
auto_now=timezone.now
)
season = models.ForeignKey(
Season,
on_delete=models.CASCADE,
related_name="season"
)
age_category = models.ForeignKey(
AgeCategory,
on_delete=models.CASCADE,
related_name="age_category"
)
def __str__(self):
return self.name
And here are serializers:
class TeamSerializer(serializers.ModelSerializer):
competition = CompetitionSerializer()
class Meta:
model = Team
fields = ("id", "club", "name", "deputy", "competition", "last_updated")
class CompetitionSerializer(serializers.ModelSerializer):
season = SeasonSerializer(read_only=True)
age_category = AgeCategorySerializer(read_only=True)
class Meta:
model = Competition
fields = ("__all__")
When I make GET request I receive output like this:
{
"id": 1,
"club": 1,
"name": "Vive Kielce",
"deputy": null,
"competition": {
"id": 1,
"season": {
"id": 1,
"name": "2023/2024",
"date_start": "2023-09-01",
"date_end": "2024-06-30",
"is_active": true,
"last_updated": "2024-02-08T14:57:20.908198Z"
},
"age_category": {
"id": 1,
"name": "Senior",
"last_updated": "2024-02-08T14:57:26.910396Z"
},
"name": "ORLEN Superliga",
"last_updated": "2024-02-08T14:57:48.592856Z"
},
"last_updated": "2024-02-08T14:58:45.095590Z"
},
which is fine.
Now I would like to make a POST request to create a new Team
object, but I don’t want to send full dict for competition, but I just want to use the ID of already existing object.
I used curl to make a POST request
curl -d '{"club": "1", "name": "Test Team 1", "competition": 1}' -H "Content-Type: application/json" -X POST http://localhost:8000/api/teams/
but received below error message
{"competition":{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]}}
I send dict
curl -d '{"club": "5", "name": "Chrobry Glogow", "competition": {"id": "1"}}' -H "Content-Type: application/json" -X POST http://localhost:8000/api/teams/
but got below message:
{"competition":{"name":["This field is required."]}
How can I achieve it?