Django序列化器未显示相关字段

时间:2018-12-05 17:26:09

标签: django rest django-rest-framework

我无法使“状态”字段显示在结果中。不知道为什么。

我的模特:

class City(models.Model):
   city_id = models.AutoField(primary_key=True)
   city = models.CharField(max_length=100, blank=True, null=True)
   state = models.ForeignKey('State', models.DO_NOTHING, blank=True, null=True)

   class Meta:
       managed = False
       db_table = 'city'

   def __str__(self):
       return self.city

class State(models.Model):
   state_id = models.AutoField(primary_key=True)
   state = models.CharField(max_length = 10, blank=True, null=True)

   class Meta:
       managed = False
       db_table = 'state'

我的序列化器:

class StateSerializer(serializers.ModelSerializer):
    class Meta:
        model = State
        fields = ('state_id', 'state')


class CitySerializer(serializers.ModelSerializer):
     state = StateSerializer(source='state_set', many=False, read_only = True)
   class Meta:
       model = City
       fields = ('city_id', 'city', 'state')

我的观点:

class CityList(APIView):
    # Return all the cities
   def get(self, request):
       cities = City.objects.all()
       serializer = CitySerializer(cities, many=True)
       return Response(serializer.data)

   def post(self):
       pass

我的结果JSON:

[
{
    "city_id": 242,
    "city": null
},
{
    "city_id": 754,
    "city": "CARY"
},
{
    "city_id": 2085,
    "city": "FROM YOUR"
},...

如何获取状态字段以显示在JSON结果中?有人可以帮忙吗?我有几个这样的桌子。

1 个答案:

答案 0 :(得分:0)

您在 CitySerializer 中关系不好。

城市没有州/州关系...它只有一个

CitySerializer 应该看起来像这样:

class CitySerializer(serializers.ModelSerializer):
    # Removed source.. by default it's like the field name
    # I removed also many=False because it's default

    state = StateSerializer(read_only=True)
    class Meta:
        model = City
        fields = ('city_id', 'city', 'state')