Django模型非数据库属性
大家好,
我可能犯了一个很傻的错误。
我有一个叫做 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)
我的问题是,在倒数第二个循环里的打印显示了正确的 c.attachments 的值,而紧接着的那个循环里的打印却显示了同一个记录的空值。这让我很困惑,因为这两个循环都是在处理同一个评论数组啊!
我很可能漏掉了什么明显又傻的东西,如果有人能发现问题,请告诉我。
谢谢!
--更新:
@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 个回答
-1
要把它连接到模型实例上,你需要写 self.attachments
。
-1
这两条语句之间有很大的区别。
del c.attachments[:]
而
c.attachments = []
del c.attachments[:]
实际上是重置了列表。但是,使用 c.attachments = []
是给 c.attachments
赋值一个空列表。我的意思是,其他与之关联的变量仍然会保持旧的列表。你可以通过在 Python 解释器中执行以下示例来看到这个区别。
>>>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]
希望这能帮到你。:)