我在一个视图中有以下代码:

        lp_detail = LearningPathDetail()
        pos_in_path = 1
        lp_detail.lpheader_id = pk

        lesson_ids = request.POST["lesson_ids"].split(",")

        for lesson_id in lesson_ids:
            lp_detail.id = ""
            lp_detail.lesson_id = lesson_id
            lp_detail.pos_in_path = pos_in_path
            lp_detail.save()
            pos_in_path += 1

pk是标题表中的ID,它指向标识与其关联的所有详细信息记录的标题记录.

lesson_ids is a list of DB ids that need to be inserted into the lp_detail table.

What I think the code should do (according to the manual) based on the id being blank (I have also tried setting it to None) is create the record, but instead I get an error:

Field 'id' expected a number but got ''.

以下是LearningPath Detail表的模型:

class LearningPathDetail(models.Model):
    lpheader = models.ForeignKey(LearningPathHeader, on_delete=models.CASCADE)
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True)
    pos_in_path = models.IntegerField(default=1)

我不确定我在这里有什么不正确的.

推荐答案

为什么要将值id设置为空字符串?只需删除此行:

lp_detail.id = ""

让Django 自己找到好的身份.

另外,我想你想要这个:

lp_detail = LearningPathDetail()

在循环内部.您可能在每次迭代时都需要新对象.

Database相关问答推荐

如何调试Anylogic SQL数据库TLS错误?

在多组MongoDB中查找最新文档的有效方法

使用Postgres获取带有表架构的外键

聚合以过滤 MongoDB 中的引用

即使将enable_seqscan设置为关闭,也未使用数组列上的 GIN 索引?

Active Record - 获取数据库中的第二个、第三个.. 项(无 ID)

实体关系图. IS A 关系如何转换为table表?

免费的 SQL 比较工具

为什么null不等于null false

将 Redis 数据同步到 MySQL 的最佳策略是什么?

什么是本体数据库?

使用 typeORM 搜索早于日期的数据

如何在磁盘上布局 B-Tree 数据?

在 Heroku 生产站点上清除 Rails 应用程序数据库

限制一个 sqlite 表的最大行数

Grails 中的 SQL/数据库视图

A QuerySet 按聚合字段值

在mysql中 Select 不同的2列组合

SQLite3 UNIQUE 约束失败错误

SQLite3 数据库的最大连接数是多少?