相关疑难解决方法(0)

Django REST Framework中的外键值

models.py:

class Station(models.Model):
    station = models.CharField()

class Flat(models.Model):
    station = models.ForeignKey(Station, related_name="metro")
    # another fields
Run Code Online (Sandbox Code Playgroud)

然后在serializers.py中:

class StationSerializer(serializers.ModelSerializer):
    station = serializers.RelatedField(read_only=True)

    class Meta:
        model = Station


class FlatSerializer(serializers.ModelSerializer):
    station_name = serializers.RelatedField(source='station', read_only=True)

    class Meta:
        model = Flat
        fields = ('station_name',)
Run Code Online (Sandbox Code Playgroud)

我有一个错误:

NotImplementedError:RelatedField.to_representation()必须实现.如果要从REST框架版本2升级,则可能需要ReadOnlyField.
我看了这个,但它对我没有帮助.
如何解决?
谢谢!

python django rest django-rest-framework

13
推荐指数
1
解决办法
6331
查看次数

PUT调用的"<Model> with this field>已经存在" - Django REST Framework

我正在进行HTTP PUT调用以使用嵌套关系更新对象的数据,并且遇到以下错误:

HTTP 400错误请求

"带有这个slug的AttributeChoice已经存在."

这是令人困惑的原因是因为我正在HTTP PUT打电话,我希望它把它视为一个UPDATE而不是一个CREATE.

我的模型看起来像这样:

class Attribute(models.Model):
    name        = models.CharField(max_length=100)
    text_input  = models.BooleanField(default=False)
    slug        = models.SlugField(unique=True)

class AttributeChoice(models.Model):
    attribute   = models.ForeignKey(Attribute)
    value       = models.CharField(max_length=100)
    slug        = models.SlugField(unique=True)
Run Code Online (Sandbox Code Playgroud)

我的Serializers看起来像这样:

class AttributeChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = AttributeChoice
        fields = '__all__'
        extra_kwargs = {'id': {'read_only': False}}

class AttributeSerializer(serializers.ModelSerializer):
    attributechoice_set = AttributeChoiceSerializer(many=True)
    class Meta:
        model = Attribute
        fields = ('id', 'name', 'text_input', 'slug', 'attributechoice_set')

    def update(self, instance, validated_data):
        choice_data = validated_data.pop('attributechoice_set') 
        for choice …
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework

8
推荐指数
1
解决办法
3407
查看次数

标签 统计

django ×2

django-rest-framework ×2

python ×1

rest ×1