簡體   English   中英

如何將外鍵提交到表單中? python / django

[英]how to get submit a foreign key into a form post? python /django

實際上我沒有表單,我目前正在使用ViewSet創建API。

我有兩個模型,一個是常規用戶模型,另一個是使用用戶名為ForeignKey的creator字段的組模型。

我創建了一個序列化器,然后用它來驗證POST輸入,以某種方式我不斷收到錯誤消息

null value in column "creator_id" violates not-null constraint

我可以理解,我也測試過這是因為嘗試發布時creator_id為null,但是我確實輸入了creator_id 我是否以錯誤的方式輸入它或如何獲取外鍵以保存它?

我的團體模特是這樣的

class Group(Model):
    creator = ForeignKey(User,
                         null=True,  // I used this to test I am right with the error
                         blank=True,  // I used this to test I am right with the error
                         on_delete=CASCADE,
                         related_name="%(class)ss",
                         related_query_name="%(class)s")
    group_name = CharField(max_length=256, unique=True)
    created_at = DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.group_name

再次,我添加了null=True, blank=True是因為我想看看是否對,因為creator_id不能為null,是的,我是對的,在添加了這兩個字段之后,我沒有收到錯誤不再。

我的GroupSerializer

class GroupSerializer(ModelSerializer):
    group_id = SerializerMethodField()
    creator_name = SerializerMethodField()
    creator_id = SerializerMethodField()

    class Meta:
        model = Group
        fields = ['group_id', 'group_name', 'creator_id', 'creator_name']

    def get_group_id(self, obj):
        return obj.id

    def get_creator_name(self, obj):
        return obj.creator.tutor_name

    def get_creator_id(self, obj):
        return obj.creator.id

    def create(self, validated_data):
        return Group.objects.create(**validated_data)

我的view.py

    @csrf_exempt
    def create(self, request):
        data = GroupSerializer(data=request.data)  // this would return the `group_name` and `creator_id` I entered
        if data.is_valid():  // this would return true
            data.save()
            return Response({'status': True})
        return Response({'status': False, 'message': data.errors}, status=400)

我嘗試使用...發布

    {
        "group_name": "bridge",
        "creator_id": 1
    }

嘗試使用"creator_id": "1""creator": "1"

仍然出現相同的錯誤...

我該如何解決?

提前致謝

我認為您在聲明序列化器錯誤。 您正在使用ModelSerializer,但是您在字段列表中聲明的字段與模型的字段不匹配。 另請注意, fields是列表,而不是數組。 我認為應該是這樣的。

class Group(Model):
    creator = ForeignKey(User,
                         on_delete=CASCADE,
                         related_name="%(class)ss",
                         related_query_name="%(class)s")
    group_name = CharField(max_length=256, unique=True)
    created_at = DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.group_name

class GroupSerializer(ModelSerializer):
    class Meta:
        model = Group
        fields = ('creator', 'group_name', 'created_at')

我也知道您正在測試它,但是在同一個字段上同時聲明null=Trueblank=True被認為是不好的做法。 應該是其中之一。

請參閱此處的文檔: http : //www.django-rest-framework.org/api-guide/serializers/#modelserializer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM