如何将django api与foreignkey一起使用

时间:2019-03-07 09:49:14

标签: django django-rest-framework django-forms django-views

我尝试将外键保存在Django restframework序列化程序中。

我的目标是将iframely.com中的信息保存在数据库中,这一部分效果很好。但我还需要将其保存在特定类别中。添加字段“ Board(我的类别名称字段)”后,我出现错误:列“ board_id”中的空值违反了非空约束

我的模特:

class Embed(models.Model):
    url = models.URLField(max_length=255)
    title = models.CharField(max_length=255)
    description = models.TextField()
    thumbnail_url = models.URLField(max_length=255)
    html = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name='Kategoria')

表格:

class SubmitEmbed(forms.Form):
    url = forms.URLField()
    board = forms.ModelChoiceField(queryset=Board.objects.all())

序列化器:

class EmbedSerializer(serializers.ModelSerializer):
    author = serializers.HiddenField(default=serializers.CurrentUserDefault())
    board = serializers.RelatedField(read_only=True)

    class Meta:
        model = Embed
        fields = '__all__'

查看:

def save_embed(request):

    if request.method == "POST":
        form = SubmitEmbed(request.POST)
        if form.is_valid():
            url = form.cleaned_data['url']
            r = requests.get('http://iframe.ly/api/oembed?url=' + url + '&key=' + settings.IFRAMELY_KEY)
            json = r.json()
            serializer = EmbedSerializer(data=json, context={'request': request})
            if serializer.is_valid():
                embed = serializer.save()
                return render(request, 'embed/embeds.html', {'embed': embed})
    else:
        form = SubmitEmbed()

    return render(request, 'embed/embedadd.html', {'form': form})

1 个答案:

答案 0 :(得分:0)

是因为您拥有

class EmbedSerializer(serializers.ModelSerializer):
    author = serializers.HiddenField(default=serializers.CurrentUserDefault())
    board = serializers.RelatedField(read_only=True)

您已将委员会设置为read_only。提供此字段并进行DRF验证后,DRF将删除此字段。

您可以删除整行,它将起作用。