У меня есть HyperlinkedModelSerializer
модели с ForeignKey
, и я хочу вернуть гиперссылку на экземпляр, указанный в этом поле, но я получаю весь объект, вложенный в json.
Это мои модели:
class Hotel(models.Model):
ONE_STAR = '*'
TWO_STARS = '**'
THREE_STARS = '***'
FOUR_STARS = '****'
FIVE_STARS = '****'
GRAND_TOURISM = 'GRAND_TOURISM'
NA = 'NA'
SPECIAL = 'SPECIAL'
ECO = 'ECO'
BOUTIQUE = 'BOUTIQUE'
HOTEL_CATEGORY_CHOICES = (
(ONE_STAR, _('*')),
(TWO_STARS, _('**')),
(THREE_STARS, _('***')),
(FOUR_STARS, _('****')),
(FIVE_STARS, _('*****')),
(GRAND_TOURISM, _('Grand Tourism')),
(NA, _('NA')),
(SPECIAL, _('Special')),
(ECO, _('Eco-Hotel')),
(BOUTIQUE, _('Boutique-Hotel'))
)
company = models.OneToOneField(Company, on_delete=models.CASCADE, primary_key=True, verbose_name=_('Company'))
code = models.CharField(max_length=10, verbose_name=_('Code'))
city = models.ForeignKey(City, on_delete=models.PROTECT, related_name='hotels', verbose_name=_('City'))
category = models.CharField(max_length=20, choices=HOTEL_CATEGORY_CHOICES, verbose_name=_('Category'))
capacity = models.IntegerField(verbose_name=_('Capacity'))
position = models.DecimalField(max_digits=11, decimal_places=2, default=0.00, verbose_name=_('Position'))
in_pickup = models.BooleanField(default=False, verbose_name=_('In pickup?'))
is_active = models.BooleanField(default=True, verbose_name=_('Is active?'))
class Meta:
verbose_name = _('Hotel')
verbose_name_plural = _('Hotels')
def __str__(self):
return self.company.name
class Company(models.Model):
name = models.CharField(max_length=40, verbose_name=_('Name'))
legal_name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_('Legal name'))
tax_id = models.CharField(max_length=12, null=True, blank=True, verbose_name=_('Tax ID'))
url = models.URLField(null=True, blank=True, verbose_name=_('URL'))
address = models.TextField(max_length=400, null=True, blank=True, verbose_name=_('Address'))
class Meta:
verbose_name = _('Company')
verbose_name_plural = _('Companies')
def __str__(self):
return "[{}]{}".format(self.id, self.name)
Это мой сериализатор:
class HotelProductsSerializer(serializers.HyperlinkedModelSerializer):
company = CompanySerializer()
products = serializers.SerializerMethodField()
def get_products(self, instance):
queryset = [product for product in instance.company.products.all()]
return ProductSerializer(queryset, many=True, context=self.context).data
class Meta:
model = models.Hotel
fields = ('company', 'products')
Это мой ViewSet:
class HotelProductsViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
queryset = models.Hotel.objects.all()
serializer_class = serializers.HotelProductsSerializer
Все отлично работает, но поле company
приводит к вложенному объекту Company, и я хотел бы вместо этого получить гиперссылку на этот объект.
Спасибо за вашу помощь.