Django Rest框架中的用户外键

时间:2020-10-09 08:20:58

标签: django django-rest-framework

我有一个用户模型和Accesskey模型。我想将正在访问API(access_key)的用户保存在accesskey表中。

models.py

C

serializers.py

class AccessKeys(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user',null=True)
    access_keys =models.CharField(max_length=400)


    def __str__(self):
        return self.access_keys

views.py

class AccessKeySerializer(serializers.ModelSerializer):
    user_id = serializers.RelatedField(source='CustomUser', read_only=True)
    access_keys = serializers.CharField(max_length=200,required=True)
    class Meta:
        model =AccessKeys
        fields = '__all__'
 

当我在模型中保存访问密钥时,user_id字段中的值为空。

0 个答案:

没有答案