python - 如何在没有表单的情况下直接在django中将项目添加到数据库

标签 python django database

我知道,这个问题已经讨论过了,但我无法捕获它。

我有两个模型

# 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 text to Text.

关于python - 如何在没有表单的情况下直接在django中将项目添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63775493/

相关文章:

python - 我可以在 python 中集成多个列表吗?

python - 如何使用 python 连接到外部 API?

python - 将服装二进制数据文件读入 pandas 数据帧

django - 使用 @user_passes_test 装饰器测试重定向

android - 每个表都需要一个 CursorAdapter 吗?

c# - 从 C# 中的多个表的查询中检索数据

python - CNN 输入中的 ValueError

javascript - Django 将数据发送到模板中的 Javascript

django - 使用 Django South 向现有模型添加自动增量字段?

c# - Entity Framework 连接到 Oracle : ODP for . NET "does not support time"