How Do I Create A View Different Than The Model With Django-rest-framework
Solution 1:
Nested Servers:
If you want (almost) exactly the output you gave as a sample, then it would be this:
classServersSerializer(serializers.ModelSerializer):
classMeta:
model = Serversfields= ('id', 'hostname')
classDatacenterSerializer(serializers.ModelSerializer):
servers = ServersSerializer(source='servers_set')
classMeta:
model = Datacenterfields= ('id', 'name')
If you want to show all fields for both models, then just drop the 'fields' line.
This could also work without the source keyword argument, but would require the related name to match the 'servers' property name (you could do this by adding related_name='servers' to the datacenter field on the Servers model).
The docs for DRF are pretty good, the bits you care about are serializer relations
Deep URL:
To achieve the nested URL structure, you could simply make an url pattern that matches the above like so:
url(r'^datacenter/(?P<datacenter_id>\d+)/Servers$', 'views.dc_servers',name="dc_servers")
which would call your view with the ID of the Datacenter as the kwarg datacenter_id
. You would then use that ID to filter the queryset of your view by datacenter_id.
You'll have to look into how to write that view yourself, here are the views docs to get you started.
A couple of general Django tips: Models should usually have singular names rather than plural and adding a related_name argument is usually a good thing (explicit over implicit).
Solution 2:
To show the Servers you can do this on the serializer:
classDatacenterSerializer(serializers.HyperlinkedModelSerializer):
servers = serializers.HyperlinkedRelatedField(
many=True
)
classMeta:
model = Datacenterfields= ('id','name', 'servers')
If you want to show several fields of the servers, you should create a ServerSerializer with the fields that you want to show and then replace the line:
servers = serializers.HyperlinkedRelatedField(
many=True
)
With:
servers = ServerSerializer(many=True)
For further information have a look at the doc: http://www.django-rest-framework.org/api-guide/relations/
Solution 3:
Thanks you both for your answers, finally all I had to do was add the related_name in the model, now it looks like this;
class Datacenter(models.Model):
name = models.CharField(max_length=50)
status = models.CharField(max_length=50)
def__unicode__(self):
returnself.name
class Servers(models.Model):
datacenter = models.ForeignKey(Datacenter,related_name="servers")
hostname = models.CharField(max_length=50)
def__unicode__(self):
returnself.hostname
Regarding the deep URL, I was checking the documentation and it should be possible to accomplish using a SimpleRouter, but couldn't find any example to see how to implement it; {prefix}/{lookup}/{methodname}/
Post a Comment for "How Do I Create A View Different Than The Model With Django-rest-framework"