'How can I add two related nested instance in one request using DRF?
Hi I'm new to Django rest framework
I have two models:
class Location(models.Model):
name = models.CharField(("name"), max_length=50)
long = models.CharField(("longitude"), max_length=50)
lat = models.CharField(("latitude"), max_length=50)
def __str__(self):
return self.name
class Farm (models.Model):
name = models.CharField(("Name"), max_length=50)
size = models.FloatField('Size')
size_unit = models.CharField(("Size Uint"), max_length=50)
owner = models.ForeignKey(Account, on_delete=models.SET('Deleted user'))
location = models.ForeignKey(Location, on_delete=models.SET('Deleted Location'))
def __str__(self):
return self.name
And serializers:
class FarmSerializer(serializers.ModelSerializer):
class Meta:
model = Farm
fields = '__all__'
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = '__all__'
How can I create both Farm and location in one request like this:
{
"name": "new farm",
"size": 400,
"size_unit": "meter",
"owner": 1,
"location":[
{
"name":"new location",
"long":2132.123212,
"lat":2213231.1234
}
]
}
I've tried to add create at serializer like:
def create(self,validated_date):
location_data = validated_date.pop('location')
location = Location.objects.get_or_create(**location_data)
farm = Farm.objects.create(**validated_date,location=location)
return farm
But it does not work and it gives me this message
{
"location": [
"Incorrect type. Expected pk value, received list."
]
}
Solution 1:[1]
First, you need to set the LocationSerializer
in FarmSerializer
.
class FarmSerializer(serializers.ModelSerializer):
location = LocationSerializer(required = True)
class Meta:
model = Farm
fields = '__all__'
And I think Farm
model has only one Location
, so the location
is not the array in JSON data.
{
"name": "new farm",
"size": 400,
"size_unit": "meter",
"owner": 1,
"location":{
"name":"new location",
"long":2132.123212,
"lat":2213231.1234
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David Lu |