In my Django App I am using a model serializer for the API to get read access tot he objects in the DB. For one API call I have to provide data from different, but related objects in one result.
class Car(models.Model):
name = models.Charfield()
class Driver(models.Model):
name = models.Charfield()
car = ForeignKey(Car, on_delete=models.CASCADE, null=Fals, blank=False)
The problem I have is that I always get back a list instead of a single object if I use nested serializers.
For example
class CarSerializer(serializers.ModelSerializer):
driver = DriverSerilizer(source='driver_set', many=True, read_only=True)
gives back a list with one item if there is a driver. If I set "many=False" I get a list with one driver object where all values are null.
So I use a MethodSerializer now to get the first Item in the list, but that seems to be like a lame solution to me.
driver = serializers.SerializerMethodField()
def get_driver(self, obj):
driver_list = DriverSerilizer(obj.driver_set.all(), many=True).data
driver = None
if len(driver_list) ==1:
driver = driver_list[1]
return driver
So it works, but isn't there a better way?
CodePudding user response:
That happens because you added a car as ForeignKey
instead of OneToOneField
,
Django expected that you might add another or a lot of cars for one driver, However, if you make it OneToOneField
then the driver mustn't have more than one car, Therefor at the OneToOneField
case it should return a single field instead of a list and if you try to add many=True
It would raise an error.