即使在“保存”之后,Django对象也不会保存。呼叫 [英] Django object not saving even after "save" call

查看:74
本文介绍了即使在“保存”之后,Django对象也不会保存。呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很茫然,因为这根本没有道理。我称之为保存/创建对象,但该对象未显示在管理网站中。我什至使用SQLite Viewer程序检查了SQLite数据库,该程序再次显示该项目尚未保存。



这是保存数据对象:

  data = Data(represents = field,for_entry = entry,value =这可以是任何东西)
#字段是DataField数据库对象,而entry是Entry数据库对象(请参见下面的模型和段落)
print( B4,data)#< ----显示未为数据分配ID / pk
data.save()
print( 8ER:,data)#< ---显示已为数据分配ID / pk

从我的评论中可以看出,我知道在<$之后,为Data对象分配了ID c $ c> save 调用,我认为这有效。没有错误抛出任何地方。 字段条目都是这两者。每个人似乎都可以,因为它们具有正确的ID,是使用 [表名] .objects.get(id = ...)检索的,我可以保存/编辑它们,并保存更改。



甚至很奇怪,这个函数中的确切代码在此函数工作之前就被调用。



这是我的model.py(我删除了一些函数使其更短):

  class Entry(models.Model):
parent = models.ForeignKey('Entry',blank = True,null = True,default = None)#此条目的条目。对于顶级条目,保留为空白。
id_number = models.CharField(max_length = 20)
visible = models.BooleanField()
data_field = models.ForeignKey('DataField',默认值= 1)#整个条目的字段跌倒了。多余但必需的

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','外键'),('r','根'),('bb','分支') ,('i','Image'),('ff','File'),('h','Holder'),('bt','Big Text'))#一个数字表示它是一个外来字符键。应该掉标题。
foreign_source = models.ForeignKey('DataField',null = True,blank = True)#指向数据字段的匹配数据将组成选项
data_type = models.CharField(max_length = 2,选择= DATA_TYPES,默认='t',null =正确,空白=真实)
标题= models.CharField(max_length = 100,null =真实,空白=真实)
可见性= models.BooleanField(默认= False)

def __str __(self):
return str(self.id)+- + str(self.title)

def __eq __( self,other):
如果不是isinstance(other,DataField):
返回False
如果self.data_type =='h':
返回self.title == other。 title
return self.id == other.id


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

def __str __(self):
返回自身.repre sents.title +- + str(self.for_entry.id)+- + str(self.value)+- + str(self.id)

可能我遗漏了一些明显的内容,或者您​​可能需要更多的信息以解决该问题。如果没有足够的信息,请发表评论并索取更多信息,或者仅列出可能发生的问题。

解决方案

I在执行单元测试时遇到了类似的问题,并且遇到了一个错误,该错误似乎表明保存方法不起作用->如下所示

  p = MyModel.objects.get(pk = myparam)
self.assertEqual(p.my_attr,value)
myfunc()#更改同一对象p的代码引用了
self .assertEqual(p.my_attr,new_value)

即使我更改了被引用的对象,上述操作仍然失败



要解决此问题,我必须将p重新分配给MyModel对象。我在单元测试中的固定代码看起来像这样。

  p = MyModel.objects.get(pk = myparam)
self.assertEqual(p.my_attr,value)
myfunc()#更改同一对象p的代码引用了
p = MyModel.objects.get(pk = myparam)
self.assertEqual(p.my_attr,new_value)

该变量似乎指向内存中的旧位置,但我才在5个月前才开始编程因此,我有些烦恼:)如果有人能解释为什么发生这种情况,因为我仍然感到困惑,我将不胜感激。



如果您真的不要以为save方法正在执行,您可以通过覆盖save方法并添加一条print语句来进行健全性检查。它看起来可能类似于以下内容:

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

def save(self,* args,** kwargs):
super(MyModel,self).save(* args,** kwargs)
打印('此属性是否已更新?(attr):',self.attr)
print('Save方法已执行!')

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

 在[ 3]:a = 1 
在[4]中:b = a
在[5]中:hex(id(a))
输出[5]:'0x100240280'
在[6]中:hex(id(b))
Out [6]:'0x100240280'
在[7]中:a = 2
在[8]中:b
Out [8]:1
In [9]:十六进制(id(a))
Out [9]:'0x1002402a0'
In [10]:十六进制(id(b))
Out [10]:'0x100240280'

我还是很想听听别人的想法。 / p>

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.

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.

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):

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.

解决方案

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.

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.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.

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:

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.

这篇关于即使在“保存”之后,Django对象也不会保存。呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆