fc4930a49e
Event-based urls - Add viewset mixin 'EventUrlViewSetMixin' to get the event from the 'event_pk' url kwarg of a view. - Add url serializer fields for object which can be accessed with a root-level and/or event-specific url ('EventHyperlinked*Field). Update viewsets and serializers to use these + clean inheritance viewsets.
33 lines
938 B
Python
33 lines
938 B
Python
from rest_framework import serializers
|
|
from rest_framework.reverse import reverse
|
|
|
|
|
|
class EventHyperlinkedFieldMixin:
|
|
|
|
def get_url(self, obj, view_name, request, format):
|
|
url_kwargs = {'pk': obj.pk}
|
|
if getattr(obj, 'event', None):
|
|
url_kwargs['event_pk'] = obj.event.pk
|
|
return reverse(
|
|
view_name, kwargs=url_kwargs, request=request, format=format)
|
|
|
|
def get_object(self, view_name, view_args, view_kwargs):
|
|
lookup_kwargs = {
|
|
'pk': view_kwargs['pk'],
|
|
'event_id': view_kwargs.get('event_pk'),
|
|
}
|
|
return self.get_queryset().get(**lookup_kwargs)
|
|
|
|
|
|
class EventHyperlinkedRelatedField(
|
|
EventHyperlinkedFieldMixin,
|
|
serializers.HyperlinkedRelatedField,
|
|
):
|
|
pass
|
|
|
|
|
|
class EventHyperlinkedIdentityField(
|
|
EventHyperlinkedFieldMixin,
|
|
serializers.HyperlinkedIdentityField
|
|
):
|
|
pass
|