我知道,这个问题已经讨论过了,但我无法捕获它。
我有两个模型
# Create your models here.
GENDER_CHOICES = [
('Male', 'M'),
('Female', 'F')]
class upload(models.Model):
name = models.CharField(max_length=100,null=True)
gender = models.CharField(max_length=10,null=True, choices=GENDER_CHOICES)
phone = models.CharField(max_length=50,null=True)
email= models.EmailField(max_length=50,null=True)
file=models.FileField(upload_to='uploads/',null=True)
def __str__(self):
return self.name
class text(models.Model):
texts=models.CharField(max_length=200,null=True,blank=True)
upload_text=models.ForeignKey(upload, blank=True, null=True, on_delete = models.CASCADE)
我有一个用于模型上传
的表单。我插入了数据和一个音频文件。然后我希望将此音频文件转换为文本并将文本保存在数据库中。
为此,我创建了另一个模型 text
。
但我不知道如何将与在模型 upload
中输入的信息相关的文本插入此模型
这是我的 views.py 文件函数
def display(request):
print('display functio')
d=upload.objects.last()
test=sr.takeCommand(d.file.path)
print(test) **# I can see text here**
p = text.objects.create(texts=test)
p.save(force_insert=True)
print(test)
return render(request,'thanks.html',{'print':test})
但是我无法进入。它抛出一个错误
UNIQUE 约束失败:sub_app_text.id
最佳答案
这是因为您插入了它两次。 .create(…)
method [Django-doc]已经插入在数据库中。所以你可以将其实现为:
def display(request):
print('display functio')
d=upload.objects.last()
test=sr.takeCommand(d.file.path)
# will store the record in the database
p = text.objects<b>.create(texts=test)</b>
print(test)
return render(request,'thanks.html',{'print':test})
你可以通过以下方式将它链接到 d
:
def display(request):
print('display functio')
d=upload.objects.last()
test=sr.takeCommand(d.file.path)
# will store the record in the database
p = text.objects<b>.create(texts=test, upload_text=d</b>)
print(test)
return render(request,'thanks.html',{'print':test})
Note: Models in Django are written in PerlCase, not snake_case, so you might want to rename the model from
totext
Text
.
关于python - 如何在没有表单的情况下直接在django中将项目添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63775493/