mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-09 16:10:50 +03:00
Improved Serializer relations docs
This commit is contained in:
parent
8cae462b3a
commit
7df11078ee
|
@ -255,7 +255,7 @@ For example, the following serializer:
|
||||||
class TrackSerializer(serializers.ModelSerializer):
|
class TrackSerializer(serializers.ModelSerializer):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Track
|
model = Track
|
||||||
fields = ('order', 'title')
|
fields = ('order', 'title', 'duration')
|
||||||
|
|
||||||
class AlbumSerializer(serializers.ModelSerializer):
|
class AlbumSerializer(serializers.ModelSerializer):
|
||||||
tracks = TrackSerializer(many=True, read_only=True)
|
tracks = TrackSerializer(many=True, read_only=True)
|
||||||
|
@ -293,7 +293,7 @@ Be default nested serializers are read-only. If you want to to support write-ope
|
||||||
class TrackSerializer(serializers.ModelSerializer):
|
class TrackSerializer(serializers.ModelSerializer):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Track
|
model = Track
|
||||||
fields = ('order', 'title')
|
fields = ('order', 'title', 'duration')
|
||||||
|
|
||||||
class AlbumSerializer(serializers.ModelSerializer):
|
class AlbumSerializer(serializers.ModelSerializer):
|
||||||
tracks = TrackSerializer(many=True)
|
tracks = TrackSerializer(many=True)
|
||||||
|
@ -405,13 +405,15 @@ In this case we'd need to override `HyperlinkedRelatedField` to get the behavior
|
||||||
def get_url(self, obj, view_name, request, format):
|
def get_url(self, obj, view_name, request, format):
|
||||||
url_kwargs = {
|
url_kwargs = {
|
||||||
'organization_slug': obj.organization.slug,
|
'organization_slug': obj.organization.slug,
|
||||||
'customer_pk': obj.pk
}
|
'customer_pk': obj.pk
|
||||||
|
}
|
||||||
return reverse(view_name, url_kwargs, request=request, format=format)
|
return reverse(view_name, url_kwargs, request=request, format=format)
|
||||||
|
|
||||||
def get_object(self, view_name, view_args, view_kwargs):
|
def get_object(self, view_name, view_args, view_kwargs):
|
||||||
lookup_kwargs = {
|
lookup_kwargs = {
|
||||||
'organization__slug': view_kwargs['organization_slug'],
|
'organization__slug': view_kwargs['organization_slug'],
|
||||||
'pk': view_kwargs['customer_pk']
}
|
'pk': view_kwargs['customer_pk']
|
||||||
|
}
|
||||||
return self.get_queryset().get(**lookup_kwargs)
|
return self.get_queryset().get(**lookup_kwargs)
|
||||||
|
|
||||||
Note that if you wanted to use this style together with the generic views then you'd also need to override `.get_object` on the view in order to get the correct lookup behavior.
|
Note that if you wanted to use this style together with the generic views then you'd also need to override `.get_object` on the view in order to get the correct lookup behavior.
|
||||||
|
|
Loading…
Reference in New Issue
Block a user