Django模型非db属性

时间:2012-01-17 20:42:42

标签: python django-models

民间 我最有可能犯了一个愚蠢的错误。

我有一个名为Comment的模型 - 一个常规模型 - 除了我想在模型中存储一个数组(数组没有存储在数据库中)。

现在我的代码看起来像:

class Comment(model.Model):
  # regular attributes such as id etc.
  #...
  attachments = [] # the attribute I would populate separately

# later...
comments = Comment.objects.filter(...)

comment_attachments_arr = [some array initialized from db separately]

# set the attribute after retrieving from the db

for c in comments:
    comment_attachments_arr = comment_attachments.get(c.id)
    del c.attachments[:] # reset the attachments array
    if comment_attachments_arr:
        c.attachments.extend(comment_attachments_arr)        
    print 'INSIDE for comment id: %s, comment attachments: %s' %( c.id, c.attachments)

for c in comments:
    print 'OUTSIDE for comment id: %s, Comment attachments: %s\n' %( c.id, c.attachments)

我的问题是第二个for循环内部的打印显示了c.attachments的正确值 - 而紧接着的for循环内部的打印显示了同一记录的空值。这是意料之外的,因为两个循环都在同一个注释数组上!

我很可能遗漏一些明显而愚蠢的东西 - 如果有人能发现问题,请回复。

感谢名单!

- 更新:

@Anurag

您的建议似乎不起作用。如果循环查询集导致另一个查询,似乎真的不直观 - 也许django总是想要获取最新数据。

无论如何,我尝试了以下方法:

comments_list = list(comments)
for c in comments_list:
    comment_attachments_arr = comment_attachments.get(c.id)
    del c.attachments[:] # clear the attachments array
    print 'BEFORE INSIDE for comment id: %s, comment attachments: %s' %( c.id, c.attachments)
    if comment_attachments_arr:
        c.attachments.extend(comment_attachments_arr)        
    print 'INSIDE for comment id: %s, comment attachments: %s' %( c.id, c.attachments)

print '\n\nFINAL comment attachments ---'
for c in comments_list:
    print 'OUTSIDE for comment id: %s, Comment attachments: %s\n' %( c.id, c.attachments)

更新2:

我不确定为什么,但如果我用行代替

它就有效
del c.attachments[:] 

c.attachments = []

直到8个小时我才回答这个答案..

2 个答案:

答案 0 :(得分:-1)

要将其附加到模型实例,您需要编写self.attachments

答案 1 :(得分:-1)

这两个陈述之间存在巨大差异。

del c.attachments[:]

c.attachments = []

del c.attachments[:]实际上会重置列表。但是,通过执行c.attachments = [],会将空白列表分配给c.attachments。通过这个,我的意思是其他变量绑定仍然有旧列表。您可以通过在python shell中执行以下示例来查看差异。

>>>a=[1,2,3]
>>>b=a               #b is also [1,2,3]
>>>del a[:]          #after this both would be []

>>>a=[1,2,3]
>>>b=a               #b is also [1,2,3]
>>>a=[]              #after this a would be [] and b would be [1,2,3]

我希望这会帮助你。 :)