使用 Django REST 框架序列化程序将 JSON 请求保存到数据库
Posted
技术标签:
【中文标题】使用 Django REST 框架序列化程序将 JSON 请求保存到数据库【英文标题】:Use Django REST framework serializer to save JSON requests to database 【发布时间】:2021-05-12 22:16:48 【问题描述】:我对 Django 完全陌生,出于某种原因,我不得不直接跳到 Django REST 框架。 我想将作为 POST 请求发送的 JSON 对象保存在我的数据库中。 JSON 对象如下所示:
[
"title": "Bitcoin Price Likely to Reach $50K Soon According to This Indicator",
"description": "",
"date": "2021-02-09T09:08:58Z",
"link": "https://cryptopotato.com/bitcoin-price-likely-to-reach-50k-soon-according-to-this-indicator/",
"keywords": [
"name": "bitcoin"
],
"source": "https://cryptocompare.com"
,
"title": "Post-Tesla News FOMO Helps Bitcoin Price to Surge Above $48,000",
"description": "",
"date": "2021-02-09T09:08:58Z",
"link": "https://www.cryptoglobe.com/latest/2021/02/post-tesla-news-fomo-helps-bitcoin-price-to-surge-above-48000/",
"keywords": [
"name": "bitcoin"
],
"source": "https://cryptocompare.com"
]
我这样创建模型:
class Keywords(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class News(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date = models.DateTimeField()
link = models.URLField()
keywords = models.ManyToManyField(Keywords)
source = models.CharField(max_length=30)
class Meta:
db_table = "News"
# ordering = "-date"
def __str__(self):
return self.title
序列化器:
class KeywordSerializer(serializers.ModelSerializer):
class Meta:
model = Keywords
fields = ["name"]
class NewsSerializer(serializers.ModelSerializer):
keywords = KeywordSerializer(read_only=True, many=True)
class Meta:
model = News
fields = ["title", "description", "date", "link", "keywords", "source"]
最后是我的观点:
class NewsView(APIView):
def post(self, request):
news_serializer = NewsSerializer(data=request.data, many=True)
try:
if news_serializer.is_valid():
news_serializer.save()
return Response("Created successfully", status=status.HTTP_201_CREATED)
except Exception as e:
print(e)
return Response("Error, Don't know what", status=status.HTTP_400_BAD_REQUEST)
通常我尽量不发布含糊和笼统的问题,但在这个问题中,我完全不知道如何在此处调试和查找问题。我从终端得到的唯一东西是
Bad Request: /news/
能否请您指出问题所在,并给出解决方法?
【问题讨论】:
尝试打印异常print(e.args) 谢谢,这样做了!print(e.args)
在终端中产生 ('keywords',)
!你知道关键字有什么问题吗?
【参考方案1】:
让我帮你解决这个问题。
在当前状态下,解决方案是覆盖NewsSerializer
的create
方法来创建新闻和关键字实例。
class NewsSerializer(serializers.ModelSerializer):
...
def create(self, validated_data):
keywords = validated_data.pop("keywords", None)
news, _ = News.objects.get_or_create(**validated_data)
if news:
for keyword in keywords:
keyword, _ = Keywords.objects.get_or_create(**keyword)
news.keywords.add(key)
return news
另外我会更新视图的发布方法如下:
...
def post(self, request):
for news in request.data:
serializer = NewsSerializer(news)
serializer.save(raise_exception=True)
return Response("Created successfully", status=status.HTTP_201_CREATED)
...
【讨论】:
【参考方案2】:好的,可能存在验证错误。
description 在模型中是必需的,而您传递的是空的。 >>“描述”:“”,
try:
if news_serializer.is_valid():
news_serializer.save()
return Response("Created successfully", status=status.HTTP_201_CREATED)
else:
print(news_serializer.errors)
return Response('Invalid data') # whatever you want
阅读https://www.django-rest-framework.org/api-guide/validators/#validation-in-rest-framework
【讨论】:
也修复了这个问题,但我得到的只是Bad Request: /news/
错误。 Django 不能显示更精确和信息丰富的错误吗?如果是这样,我该如何启用它?非常感谢。
参考这个***.com/questions/19875789/…以上是关于使用 Django REST 框架序列化程序将 JSON 请求保存到数据库的主要内容,如果未能解决你的问题,请参考以下文章
Django Haystack 结果到 Django Rest 框架序列化器
是否可以在 django rest 框架序列化程序中使用重用 django 表单进行验证?
从 django rest 框架中的序列化程序发送自定义错误响应?
Django rest框架 - 模型序列化程序不会序列化所有字段