如何序列化通过外键关联的模型字段?

时间:2019-07-09 14:38:22

标签: django-rest-framework

我想序列化BranchSerializer中Bank模型的名称字段。 id字段是分支模型中的外键。

我已经尝试过RelatedField:

class BankSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Bank


class BranchSerializer(serializers.HyperlinkedModelSerializer):
    bank_name = serializers.RelatedField(source=Bank, read_only=True)

    class Meta:
        model = Branch
        fields = ('ifsc', 'branch', 'address', 'city', 'district', 'state', 'bank_name')

型号:

class Bank(models.Model):
    name = models.TextField()
    id = models.IntegerField(unique=True, primary_key=True)

    class Meta:
        db_table = 'banks'
        managed = False

    def __str__(self):
        return self.name


bank = Bank()


class Branch(models.Model):
    ifsc = models.CharField(max_length=20, null=False, primary_key=True)
    bank = models.ForeignKey(Bank, on_delete=models.CASCADE)
    branch = models.CharField(max_length=50)
    address = models.TextField()
    city = models.CharField(max_length=20)
    district = models.CharField(max_length=30)
    state = models.CharField(max_length=20)

    class Meta:
        db_table = 'branches'
        managed = False

    def __str__(self):
        return '{} {}'.format(self.branch, bank.name)

序列化器:

from rest_framework import serializers
from records.models import Bank, Branch


class BankSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Bank


class BranchSerializer(serializers.HyperlinkedModelSerializer):
    bank_name = serializers.RelatedField(source=Bank, read_only=True)

    class Meta:
        model = Branch
        fields = ('ifsc', 'branch', 'address', 'city', 'district', 'state', 'bank_name')
TypeError: argument of type 'ModelBase' is not iterable

0 个答案:

没有答案