2012-01-17 75 views
0

民间 我正在犯一个愚蠢的错误最有可能。Django模型非数据库属性

我有一个模型称为评论 - 一个常规模型 - 除了我想存储模型内的数组(数组不存储在数据库中)。

现在我的代码看起来是这样的:

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) 

我的问题是,倒数第二的循环内的打印显示c.attachments正确的值 - 而里面的for循环紧随显示打印相同记录的空值。这是意想不到的,因为两个循环都在相同的注释数组上!

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

Thanx!

--update:

@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 = [] 

I c直到8小时才回应此答案。

+0

你没有'数组',你有一个列表。 Python确实有一个数组,但这不是你正在使用的。 – jknupp 2012-01-17 20:56:58

+0

@jknupp - 你想要的是哪种数据结构?评论模型中的“附件”属性?如果您正在讨论comment_attachments_arr - 它没有正确命名(对不起) - 这是一个字典,其中键为数字(id),值为数组。 – serverman 2012-01-17 21:02:24

+0

@jknupp:Python'list'是一个数组(或矢量) - 它不是一个链接的数据结构,这是大多数人在阅读“list”时会想到的。 – Marcin 2012-01-21 15:42:50

回答

-1

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

+0

不确定你的意思。附件不过是一个简单的数组,其中包含一些我试图与每个评论实例关联的数据。 – serverman 2012-01-17 21:04:43

+0

附件是您的代码中的一个类属性,在对象的实例之间共享。如果你想每个实例一个,你需要写'def __init __(self):self.attachments = []' – jknupp 2012-01-18 19:21:25

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

我希望这可以帮助你。 :)

+0

我有上面解释说我得到了一个反对票吗?如果它真的错了,我总是喜欢讨论并从中获得知识。 :) – 2012-01-21 17:38:18