民间 我正在犯一个愚蠢的错误最有可能。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小时才回应此答案。
你没有'数组',你有一个列表。 Python确实有一个数组,但这不是你正在使用的。 – jknupp 2012-01-17 20:56:58
@jknupp - 你想要的是哪种数据结构?评论模型中的“附件”属性?如果您正在讨论comment_attachments_arr - 它没有正确命名(对不起) - 这是一个字典,其中键为数字(id),值为数组。 – serverman 2012-01-17 21:02:24
@jknupp:Python'list'是一个数组(或矢量) - 它不是一个链接的数据结构,这是大多数人在阅读“list”时会想到的。 – Marcin 2012-01-21 15:42:50