[英]Nested serializer with Django-Rest-Framework
I've been trying to use a nested serializer with DRF but it won't display the related item in the output. 我一直在尝试使用带DRF的嵌套序列化程序,但它不会在输出中显示相关项。
Here's my model.py
: 这是我的
model.py
:
class Categorie(models.Model):
nom = models.CharField(max_length=100)
def __unicode__(self):
return unicode(self.nom)
class Item(models.Model):
nom = models.CharField(max_length=100)
disponible_a_la_vente = models.BooleanField(default = True)
nombre = models.IntegerField()
prix = models.DecimalField(max_digits=5, decimal_places=2)
history = HistoricalRecords()
categorie = models.ForeignKey(Categorie, models.CASCADE)
class Meta:
verbose_name = "item"
verbose_name_plural = u"inventaire"
ordering = ['categorie', 'nom']
def __unicode__(self):
return u'{nom} - {nombre}'.format(nom = self.nom, nombre = self.nombre)
and my serializers.py
和我的
serializers.py
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('nom',)
class CategorieSerializer(serializers.ModelSerializer):
items = ItemSerializer(many=True)
class Meta:
model = Categorie
fields = ('nom', 'id', 'items')
The view i'm currently testing is very basic : 我目前正在测试的视图非常基础:
class InventaireDetail(generics.RetrieveAPIView):
queryset = Categorie.objects.all()
serializer_class = CategorieSerializer
but it gives the error: 但它给出了错误:
AttributeError: Got AttributeError when attempting to get a value for field
items
on serializerCategorieSerializer
.AttributeError:尝试在序列化程序
CategorieSerializer
上获取字段items
的值时获得AttributeError。 The serializer field might be named incorrectly and not match any attribute or key on theCategorie
instance.序列化程序字段可能名称不正确,并且与
Categorie
实例上的任何属性或键都不匹配。 Original exception text was: 'Categorie' object has no attribute 'items'.原始异常文本是:'Categorie'对象没有属性'items'。
I've been looking for a while now but i can't get it working even with the help of the doc. 我一直在寻找一段时间,但即使在文档的帮助下我也无法使它工作。
Categorie.items
does not exist. Categorie.items
不存在。 By default the reverse relation would get the name Categorie.item_set
. 默认情况下,反向关系将获得名称
Categorie.item_set
。 You can fix that in two ways. 您可以通过两种方式解决这个问题。
EITHER: add related_name
to your foreign key. EITHER:将
related_name
添加到您的外键。
class Item(models.Model):
categorie = models.ForeignKey(Categorie, models.CASCADE, related_name='items')
OR: another solution is to change the CategorieSerializer 或者:另一种解决方案是更改CategorieSerializer
class CategorieSerializer(serializers.ModelSerializer):
items = ItemSerializer(many = True, read_only=True, source='item_set')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.