1👍
✅
You should reference the options in the CarSerializer using the options field name rather than the color field name (as you set the related field to be options in the OneToOneField). You do not define a color field directly on the Car.
The following code works for me with the latest django and rest framework:
models.py
class CarModel(models.Model):
name = models.CharField(max_length=250)
class CarOptionsModel(models.Model):
car = models.OneToOneField(CarModel, related_name='options')
color = models.CharField(max_length=250)
serializers.py
class CarOptionsSerializer(serializers.ModelSerializer):
color = serializers.CharField()
class Meta:
model = CarOptionsModel
fields = ('color',)
class CarSerializer(serializers.ModelSerializer):
options = CarOptionsSerializer(read_only=True, )
class Meta:
model = CarModel
fields = ('options', 'name')
views.py
class CarViewSet(viewsets.ModelViewSet):
serializer_class = CarSerializer
queryset = CarModel.objects.all()
urls.py
router = routers.DefaultRouter()
router.register(r'api', CarViewSet)
urlpatterns = router.urls
I would note that since you define a one to one mapping, you cannot have many=True
.
Source:stackexchange.com