Let say i have two models:
level:
id
file_number
status
level_process:
process_ptr_id
level_id
I want to combine both of my table above to display it in one API using django-rest-framework.. I'm looking for the example on the internet and i cannot find it...by the way i'm using python 2.7 , django 1.10.5 and djangorestframework 3.6.2
serializer.py
class LevelSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = Level
fields = ('__all__')
class LevelProcessSerializer(serializers.ModelSerializer):
level = LevelSerializer(read_only=True)
class Meta:
model = LevelProcess
fields = ('__all__')
views.py
class ViewLevelProcessViewSet(viewsets.ModelViewSet):
processes = LevelProcess.objects.all()
serializer_class = LevelProcessSerializer(processes, many=True)
The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.
to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
Try the following. Create serializer for your Level
model:
class LevelSerializer(serializers.ModelSerializer):
class Meta:
model = Level
Then, inside LevelProcessSerializer
, include LevelSerializer
like this:
class LevelProcessSerializer(serializers.ModelSerializer):
level = LevelSerializer(read_only=True)
class Meta:
model = LevelProcess
Usage in your ModelViewset:
class ViewLevelProcessViewSet(viewsets.ModelViewSet):
queryset = LevelProcess.objects.all()
serializer_class = LevelProcessSerializer
This way, your json will look something like this:
{
"id": 1,
"level": {
"id": 3,
"status": "red"
}
}
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With