我有两个型号。现在Class Track Model有一个Album外键。 我想写一个具有专辑名称的Track Serializer。我怎样才能做到这一点?
class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks')
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ('album', 'order')
ordering = ['order']
def __unicode__(self):
return '%d: %s' % (self.order, self.title)
我将Track的深度参数设置为1,但是检索专辑名称和艺术家。我只想在Track Serializer中找到专辑名称
答案 0 :(得分:1)
有很多解决方案。您可以使用多种类型的字段e。 G。 StringRelatedField或SerializerMethodField。
以下是自定义相关字段的示例:
from rest_framework import serializers
class TrackField(serializers.RelatedField):
def to_representation(self, value):
return value.album_name
class TrackSerializer(serializers.ModelSerializer):
album = TrackField(queryset=Album.objects.all())
class Meta:
model = Track
fields = ('album', 'order', 'title', 'duration')
这会产生:
track = Track.objects.get(...)
TrackSerializer(track).data # Returns {'album': <name of the album>, ...}
答案 1 :(得分:0)
class BaseSerializer(serializers.ModelSerializer):
"""
A Base Serializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
exclude = kwargs.pop('exclude', None)
# Instantiate the superclass normally
super(BaseSerializer, self).__init__(*args, **kwargs)
if fields:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
if exclude:
# Drop fields that are specified in the `exclude` argument.
excluded = set(exclude)
for field_name in excluded:
try:
self.fields.pop(field_name)
except KeyError:
pass
我使用上面的类明确地排除了我不想要的参数,
信用:How to exclude parent when serializer is nested when using Django REST Framework?