django(rest)for model.all()从外键关系中获取字段

时间:2018-09-03 13:37:41

标签: django django-rest-framework

我有一个Report模型,该模型与Currency模型具有如下关系:

class Currency(models.Model):
    name = models.CharField(max_length=48)
    symbol = models.CharField(max_length=4)
    code = models.CharField(max_length=3)

    class Meta:
        db_table = 'currency'
        verbose_name = 'currency'
        verbose_name_plural = 'currencies'

class Report(models.Model):
    path = models.CharField(max_length=256, null=True)
    currency = models.ForeignKey(Currency, on_delete=models.CASCADE)

        class Meta:
            db_table = 'dsr'

我想在我的views.py中获取每个报告的所有货币代码。我已经尝试过使用反向查找,但是它们似乎不适用于“全部”

我的序列化器:

class CurrencySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Currency
        fields = '__all__'

,与报告序列化程序相同。我的views.py:

@api_view(['GET'])
def rep_currencies(request):
    all_reports = models.Report.objects.all()
    report_currencies = all_reports.currency_set.all()
    data = serializers.CurrencySerializer(report_currencies, many=True).data
    return Response(data)

返回“ QuerySet”对象的

没有属性“ currency_set”。

0 个答案:

没有答案