#models.py
class Color(models.Model):
name = models.CharField(max_length=100, unique=True)
finish = models.CharField(max_length=100, null=True, blank=True)
class Car(models.Model):
make = models.CharField(max_length=100, unique=True)
model = models.CharField(max_length=100, unique=True)
color = models.ForeignKey(Color)
#serializer.py
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = models.Color
fields = ('name', 'finish')
class CarSerializer(serializers.ModelSerializer):
color = ColorSerializer()
class Meta:
model = models.Car
fields = ('make', 'model', 'color')
#data to write
car_data = {
'make': 'Dodge',
'model': 'Daytona',
'color': {'name': 'black', 'finish': 'gloss'}
}
# instantiate a serializer with the data to write
mycar = serializers.CarSerializer(data=car_data)
# runs the to_internal_value, and validation methods on the fields specified
mycar.is_valid()
# Assuming the data is valid, this writes the instance to the database
mycar.save()
2) In the docs, it states, "If you want to implement a read-write relational field, you must also implement the .to_internal_value(self, data) method."
- I don't really understand what to do in the to_internal_value() method.
- The examples I have seen use it for a variety of things, but it is not clear if this is meant strictly for validation.
- Would it be used to access the self.Meta.model manager in the Color serializer, to lookup an existing Color object, and return the instance to the parent.
3) The validation automatically occurs for the nested data, by drilling down into each serializer class, but I found the create method DOES NOT appear to follow the relationship.
- When it comes to saving the validated data, the create() method is called for the serializer associated to the parent Car object.
- To handle the nested create, it seems this all needs to be done from the parent (Car) serializer; using the model manager methods (.get(), .create(), etc), for BOTH the Car and Color objects.
- Why can't the parent serializer (Car) see that a nested relationship exists, and call the nested create method?
- It seems cleaner to have the child Color.create() handle the lookup for existing or create new (Color.objects.get_or_create), and return the instance.
- Then the parent Car serializer create can finish creating the Car object with the instance returned from the Color serializer.
- This way each serializer locally handles the validation, lookup, and creation.
- If the nested depth is 5, the serializer at level1 would have a really complicated create() method.
4) ModelSerializer is nice for simple models like the example, so why would I want to convert it to a Serializer?
- I have read Tom mention mention many times to re-write the ModelSerializer as a Serializer, but I want to understand the real differences with ModelSerializer vs Serializer.
Thanks in advance,Jason