您好,我是Django的新手,我希望有人可以为我的小问题提供帮助^^
我有这样的模型:
class Article(model.Model):
name = model.CharField(max_length=100)
...
class Stock(model.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE, null=True)
quantity = model.IntegerField(max_digits=10, default=1)
quality = models.CharField(max_length=15, choices=[(tag.value, tag.value) for tag in States])
...
我想获得所有类似股票的所有文章列表
[{
name: 'Bla',
stock: [{
quantity: 22,
quality: 'good',
}]
}]
我有一个视图:
class ArticleListView(ListAPIView):
queryset = Article.objects.all()???
serializer_class = ArticleStockSerializer
permission_classes = (IsAuthenticated, HasAccess)
但是我不确定如何使用
和类似的序列化器:
class ArticleStockSerializer(ArticleSerializer):
stock = serializers.SerializerMethodField()
def get_stock(self, obj):
stock = StockSerializer()
return stock
class Meta(ArticleSerializer.Meta):
model = Article
fields = ArticleSerializer.Meta.fields + ('stock',)
无法正常工作,我找不到正确的使用方式。
希望有人可以帮助我:)
致谢
xQp
答案 0 :(得分:1)
您应该尝试使用Serializer Nested relationships
class StockSerializer(serializers.ModelSerializer):
class Meta:
model = Stock
fields = ('quantity', 'quality',)
class ArticleStockSerializer(ArticleSerializer):
stocks = StockSerializer(many=True, read_only=True)
class Meta(ArticleSerializer.Meta):
model = Album
fields = ArticleSerializer.Meta.fields + ('stocks',)