Reputation: 301
I have a problem with a model serializer. My models
class ItemState(models.Model):
"""Status for a item"""
name = models.CharField(max_length=255, null=True, blank=True)
class Item(models.Model):
title = models.CharField(max_length=255)
status = models.ForeignKey(ItemState, on_delete=models.CASCADE)
My serializer:
class ItemStateSerializer(serializers.ModelSerializer):
class Meta:
model = ItemState
fields = '__all__'
class ItemSerializer(serializers.ModelSerializer):
status = ItemStateSerializer(read_only=True)
class Meta:
model = Item
fields = '__all__'
And my viewset
class ItemViewSet(viewsets.ModelViewSet):
""" Item view set """
queryset = Item.objects.all()
serializer_class = ItemSerializer
permission_classes = (IsOwnerOrAdmin, )
My question is, how can i do a put or post without create a status object? I wanna replace this
HTTP PUT
{
"title": "example",
"status": {
"id": 1,
"name": "hello"
}
}
by this
HTTP PUT
{
"title": "example",
"status": 1
}
Thanks community!
Upvotes: 1
Views: 1119
Reputation: 12990
You can use two serializer fields for the same model field - one for details, and the other default with the id (see this answer). So in your case, your serializer can be defined as:
class ItemSerializer(serializers.ModelSerializer):
status_detail = ItemStateSerializer(source='status', read_only=True)
class Meta:
model = Item
fields = '__all__'
Now your PUT requests will be like you want:
HTTP PUT
{
"title": "example",
"status": 1
}
but when you GET an Item
, it will have ItemState
details in the status_detail
field:
HTTP GET
{
"title": "example",
"status": 1
"status_detail": {
"id": 1,
"name": "hello"
}
}
Upvotes: 1
Reputation: 17
Do you want to keep the other class or can you get rid of it all together? It seems simpler to do:
class Item(models.Model):
title = models.CharField(max_length=255)
status = models.CharField(max_length=255) # or you can change to int if you want
Upvotes: 1