【问题标题】:How to insert NULL in database using Django如何使用 Django 在数据库中插入 NULL
【发布时间】:2011-09-11 13:50:28
【问题描述】:

我在 Django 中插入 NULL 时遇到问题。我的意思是我不知道该怎么做。

我有函数,我们称它为find_position,然后我在模型中有字段,如position(IntegerField,null=True,blank=True)。这个函数检查一些 html 代码,如果它与一些正则表达式匹配,它返回整数,但如果它没有找到 - 必须返回 NULL 或 None 或我可以放入数据库的东西。

 def find_position(self, to_find, something): 
   ...
       if re.search(to_find, something): 
           return i + (page * 10) + 1 
    return NULL # or what i have to return here?

我有这个:

_position = find_position(to_find, something)
p = Result(position=_position, ...)
r.save()

以前我为position 使用CharField,如果找不到结果则返回'-'。但是我在计算总结果时遇到了问题,例如 position__lte=10(因为它不是 integer 并且它与数字和字符串 - 混淆了。

我能用这个做什么?

【问题讨论】:

    标签: database django django-models integer nullable


    【解决方案1】:

    使函数返回None(或不返回任何内容,与返回None相同),在数据库中将保存Null

     def find_position(self, to_find, something): 
       ...
           if re.search(to_find, something): 
               return i + (page * 10) + 1 
        return None
    

    【讨论】:

    • 真的很奇怪。以前试过这个,有问题。现在它起作用了!谢谢)还有一个问题,我如何将表中的所有字段(之前为 -)更改为 NULL?
    • 使用更新查询直接更新数据库中的字段,例如:UPDATE youTable Set position = NULL WHERE position = '-'
    • 或者你可以在shell中使用update()Results.objects.filter(position='-').update(position=None)
    猜你喜欢
    • 2014-09-24
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2019-02-22
    • 2011-05-13
    相关资源
    最近更新 更多