热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Django对象即使在“save”调用之后也不保存-Djangoobjectnotsavingevenafter“save”call

Imreallyatalossbecausethismakesnosenseatall.Icallsavecreateanobject,anditdosnt

I'm really at a loss because this makes no sense at all. I call save/create an object, and it dosn't show up in the admin site. I even checked the SQLite database with a SQLite Viewer program, which again showed that the item had not been saved.

我真的很迷茫,因为这毫无意义。我调用save/create一个对象,它不会出现在管理站点中。我甚至用一个SQLite查看器程序检查了SQLite数据库,它再次显示项目没有保存。

This is the code that saves the Data object:

这是保存数据对象的代码:

        data = Data(represents=field, for_entry=entry, value="This can be anything")
        # field is a DataField db object and entry is a Entry db object (see model below and paragraph)
        print("B4", data) #<---- Shows that Data has not been assigned an ID/pk
        data.save()
        print("8ER: ", data) #<--- Shows that Data has been assigned an ID/pk

As you can see from my comments, I know that the Data object is assigned an ID after the save call, which I would think meant that it worked. No error is thrown anywhere. field, and entry are all both. Each one seems to be ok, as in they have the right IDs, were retrieved with [table name].objects.get(id=...), and I can save/edit them and their saves change.

正如您从我的注释中看到的,我知道数据对象在save调用之后被分配了一个ID,我认为这意味着它可以工作。任何地方都不会抛出错误。字段和入口都是。每一个看起来都很好,就像在他们有正确的id一样,用[表名].objects.get(id=…)来检索,我可以保存/编辑它们,它们的保存更改。

Even strange, this exact code in a function that is called right before this one works.

甚至奇怪的是,在这个函数之前,这个函数的准确代码是正确的。

This is my model.py (I took out some functions to make it shorter):

这是我的模型。py(我拿出一些函数使它变短):

class Entry(models.Model):
    parent = models.ForeignKey('Entry', blank = True, null = True, default=None) #  The entry this subs. Is left blank for top level entries.
    id_number = models.CharField(max_length=20)
    visible = models.BooleanField()
    data_field = models.ForeignKey('DataField', default=1)  # The field that this entire entry falls under. REDUNDANT BUT NECISSARY

    def __str__(self):
        return str(self.id)+ "-" + str(self.id_number) 

class DataField(models.Model):
    parent = models.ForeignKey('DataField', related_name='parent field', null=True, blank=True, default=1)
    order = models.IntegerField()
    multiple_entries = models.BooleanField(default=True)
    DATA_TYPES = (('t', 'Text'), ('d', 'Date'), ('l', 'List'), ('o', 'Option'), ('b', 'Boolean'), ('f', 'Foreign Key'), ('r', 'Root'), ('bb', 'Branch'), ('i', 'Image'), ('ff', 'File'), ('h', 'Holder'), ('bt', 'Big Text'))  # A number means it is a foreign key. Should go off title.
    foreign_source = models.ForeignKey('DataField', null=True, blank=True) #  Points to DATA FIELD WHO'S MATCHING DATA WILL MAKE UP THE OPTIONS
    data_type = models.CharField(max_length=2, choices=DATA_TYPES, default='t', null=True, blank=True)
    title = models.CharField(max_length=100, null=True, blank=True)
    visibility = models.BooleanField(default=False)

    def __str__(self):
        return str(self.id) + "-" + str(self.title)

    def __eq__(self, other):
        if not isinstance(other, DataField):
            return False
        if self.data_type == 'h':
            return self.title == other.title
        return self.id == other.id


class Data(models.Model):
    represents = models.ForeignKey('DataField')
    for_entry = models.ForeignKey('Entry', null=True)
    value = models.CharField(max_length=1000000)

    def __str__(self):
        return self.represents.title + "-" + str(self.for_entry.id) + "-" + str(self.value) + "-" + str(self.id)

It's possible that I'm missing something obvious, or maybe you need way more information than I can provide to fix it. If there is not enough information, please comment and request more info, or just list possible issues that could be happening.

可能我遗漏了一些明显的东西,或者你需要的信息比我提供的要多。如果没有足够的信息,请评论并请求更多的信息,或者列出可能发生的问题。

2 个解决方案

#1


1  

Try a manual commit. I don't know what else to suggest.

尝试手动提交。我不知道还有什么建议。

from django.db import transaction

@transaction.commit_manually
def viewfunc(request):
    ...
    data.save()
    transaction.commit()

#2


1  

I had a similar issue doing a unit test and encountered an error where it appeared the save method wasn't working --> was as follows

我在做单元测试时遇到了类似的问题,并在保存方法不起作用的地方遇到了一个错误——>如下所示

p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, value) 
myfunc()  # Code that changed the same object p is referencing
self.assertEqual(p.my_attr, new_value)

The above failed even though I changed the object being referenced to the new value and then did .save() on the object.

尽管我将对象引用到新值,然后在对象上执行.save(),但上面的操作失败了。

To fix the issue, I had to reassign p to the MyModel object. My fixed code in the unit test looked something like this.

为了解决这个问题,我必须将p重新分配给MyModel对象。单元测试中的固定代码是这样的。

p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, value) 
myfunc()  # Code that changed the same object p is referencing
p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, new_value)

It appears to be an issue with the variable pointing to an old location in memory, but I only started programming 5 months ago so I'm in a little over my head :) I would really appreciate feedback if anyone can explain why this is happening as I'm still stumped.

这似乎是一个问题,这个变量指向内存中的一个旧位置,但是我在5个月前才开始编程,所以我有点过了头:如果有人能够解释为什么会发生这样的事情,我将非常感激,因为我仍然被难住了。

If you REALLY don't think the save method is executing, you can do a sanity check by overwriting the save method and add a print statement. It might look similar to the following:

如果您真的不认为save方法正在执行,那么您可以通过重写save方法并添加print语句来进行完整性检查。它可能类似于以下内容:

class MyModel(models.Model):
    attr = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        super(MyModel, self).save(*args, **kwargs)
        print('Did this attribute update? (attr):', self.attr)
        print('Save method executed!')

EDIT: Inline with the memory location theory, I made this simple example:

编辑:与内存位置理论一致,我做了一个简单的例子:

In [3]: a = 1
In [4]: b = a
In [5]: hex(id(a))
Out[5]: '0x100240280'
In [6]: hex(id(b))
Out[6]: '0x100240280'
In [7]: a = 2
In [8]: b
Out[8]: 1
In [9]: hex(id(a))
Out[9]: '0x1002402a0'
In [10]: hex(id(b))
Out[10]: '0x100240280'

Would still love to hear anyones thoughts.

还是很想听听别人的想法。


推荐阅读
author-avatar
人对方啥地位
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有