Как получить только одно поле из обратной ссылки в Django Rest Framework - PullRequest
0 голосов
/ 22 мая 2018

У меня есть две модели, Roundtrip и Tour, и еще одна модель под названием RoundtripTour, где я могу связать эти две модели многими многими.Я сделал службу отдыха, которая возвращает экземпляр Tour и список всех экземпляров RoundtripTour через обратную ссылку, и она работает отлично, но служба возвращает все поля из модели RoundtripTour, и я хочу вернутьтолько поле, которое ссылается на экземпляр модели Roundtrip.

Это мои модели:

class Roundtrip(models.Model):
    name = models.CharField(max_length=70, verbose_name=_('Name'))
    code = models.CharField(max_length=8, verbose_name=_('Code'))
    duration = models.IntegerField(verbose_name=_('Duration'))
    description = models.TextField(verbose_name=_('Description'))

class Tour(models.Model):
    name = models.CharField(max_length=70, verbose_name=_('Name'))
    description = models.TextField(verbose_name=_('Description'))
    is_own = models.BooleanField(default=True, verbose_name=_('Is own tour?'))
    code = models.CharField(max_length=10, verbose_name=_('Code'))

class RoundtripTour(models.Model):
    roundtrip = models.ForeignKey(Roundtrip, on_delete=models.PROTECT, related_name='tours', verbose_name=_('Roundtrip'))
    tour = models.ForeignKey(Tour, on_delete=models.PROTECT, related_name='roundtrips', verbose_name=_('Tour'))
    day = models.IntegerField(verbose_name=_('Day'))

Это мой сериализатор:

class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer):
    roundtrips = serializers.SerializerMethodField()

    def get_roundtrips(self, instance):
        queryset = [x.roundtrip for x in instance.roundtrips.all()]
        return RoundtripSerializer(queryset, many=True, context=self.context).data

class Meta:
    model = models.Tour
    fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips')

Это мой взгляд:

class TourRoundtripsViewSet(viewsets.ModelViewSet):
    queryset = models.Tour.objects.all()
    serializer_class = serializers.TourRoundtripsSerializer

Мне бы хотелось, чтобы ссылка реверсора roundtrips возвращала только поле roundtrip из модели RoundtripTour (поле roundtrip модели RoundtripTour).Это возможно?

Я внес изменения, предложенные @Ykh, но получаю ошибку.Это обратная связь:

Internal Server Error: /es/reservations_manager/roundtrips/1/composition
Traceback (most recent call last):
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/mixins.py", line 58, in retrieve
    return Response(serializer.data)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 560, in data
    ret = super(Serializer, self).data
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
    self._data = self.to_representation(self.instance)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/fields.py", line 1855, in to_representation
    return method(value)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/Intellibook/ReservationsManagerApp/serializers.py", line 191, in get_hotels
    return HotelSerializer(queryset, many=True).data
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 765, in data
    ret = super(ListSerializer, self).data
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
    self._data = self.to_representation(self.instance)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation
    self.child.to_representation(item) for item in iterable
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/relations.py", line 356, in to_representation
    "the serializer." % self.__class__.__name__
AssertionError: `HyperlinkedRelatedField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.
[24/May/2018 14:23:52] "GET /es/reservations_manager/roundtrips/1/composition HTTP/1.1" 500 145268

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

Добавьте еще один сериализатор, RoundtripsSerializer, как показано ниже,

class RoundtripsSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = RoundtripTour
        fields = ('roundtrip',)


class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer):
    roundtrips = RoundtripsSerializer(many=True, read_only=True)

    class Meta:
        model = Tour
        fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips')
        depth = 1
0 голосов
/ 22 мая 2018
class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer):
    roundtrips = serializers.SerializerMethodField()

    def get_roundtrips(self, instance):
        queryset = [x.roundtrip for x in instance.roundtrips.all()]
        return RoundtripSerializer(queryset, many=True,  context=self.context).data

    class Meta:
        model = models.Tour
        fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips')
        depth = 1

используйте SerializerMethodField , чтобы получить все, что вы хотите.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...