django rest框架嵌套关系 -

时间:2015-02-17 17:59:13

标签: python django django-rest-framework

我在理解Django Rest Framework时遇到了一些麻烦。我正在构建一个应用程序,非常简单。由于某种原因,我不明白我无法使其正常工作。

我正在使用:

  • python:3.4.0
  • Django:1.7.4
  • Django Rest Framework:3.0.5

事情就是这样:

#models.py
class Country(StandardMetadata, GeoBase):
    CONTINENT_CHOICES = (
        ('OC', 'Oceania'),
        ('EU', 'Europe'),
        ('AF', 'Africa'),
        ('NA', 'North America'),
        ('AN', 'Antarctica'),
        ('SA', 'South America'),
        ('AS', 'Asia'),
    )

    name = models.CharField(max_length=200, db_index=True)
    slug = AutoSlugField(populate_from='name')
    continent = models.CharField(max_length=2, choices=CONTINENT_CHOICES, default='NA')
    iso2 = models.CharField(max_length=2)
    iso3 = models.CharField(max_length=3)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'Countries'


class Region(StandardMetadata, GeoBase):
    name = models.CharField(max_length=200, db_index=True)
    slug = AutoSlugField(populate_from='name')
    iso2 = models.CharField(max_length=2)

    country = models.ForeignKey(Country)

    def __str__(self):
        return self.get_full_name()

    def get_full_name(self):
        return ', '.join([self.name, self.country.name])

    class Meta:
        unique_together = ('slug', 'country')
        verbose_name = 'Region/State/Province'
        verbose_name_plural = 'Regions/States/Provinces'


#serializers.py
class CountrySerializer(serializers.ModelSerializer):
    class Meta:
        model = Country
        fields = ('id', 'name', 'slug', 'iso2', 'iso3', 'continent', 'lng', 'lat')


class RegionSerializer(serializers.ModelSerializer):
    country = CountrySerializer(read_only=True, required=True, many=False)

    class Meta:
        model = Region
        fields = ('id', 'name', 'slug', 'iso2', 'lng', 'lat', 'country',)

#views.py
class CountryViewSet(viewsets.ModelViewSet):
    queryset = Country.objects.all()
    serializer_class = CountrySerializer


class RegionViewSet(viewsets.ModelViewSet):
    queryset = Region.objects.all()
    serializer_class = RegionSerializer

#urls.py
router = routers.DefaultRouter()
router.register(r'countries', CountryViewSet)
router.register(r'regions', RegionViewSet)

因此,出于某种原因,当我尝试访问此网址时出现此错误(http://192.168.33.30:5000/regions/):可能无法同时设置read_onlyrequired < / p>

我错过了什么?

非常感谢你的帮助!

修改

我发现了我的一个问题。我删除了 Region 模型中的行unique_together = ('slug', 'country')。我将 slug 字段设置为唯一。第二个问题是我不得不打破我的模型以使其发挥作用。

1 个答案:

答案 0 :(得分:0)

不是在Serializer中指定只读,而是执行此操作:

class RegionSerializer(serializers.ModelSerializer):
    country = CountrySerializer(required=True, many=False)

    class Meta:
        model = Region
        fields = ('id', 'name', 'slug', 'iso2', 'lng', 'lat', 'country',)
        read_only_fields = ('country', )