フォーク 私は愚かな間違いを犯している可能性が最も高いです。Djangoモデルnon db属性
モデル内に配列を格納したい(ただし、配列はデータベースに格納されません)以外は、Comment - 通常のモデルと呼ばれるモデルがあります。
のように今、私のコードが何かになります:私の問題は、ループの最後から二番目の内部のプリントがc.attachmentsに正しい値を示していることである
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)
- すぐにショーを以下のため、ループ内の印刷に対し、同じレコードの空の値。両方のループが同じコメント配列を超えているため、これは予期しないことです!
誰かが問題を見つけられる場合は、明らかに愚かなものが見つからない可能性が高いです。返信してください。
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 = []
Icこの回答で8時間まで応答しないでください。
あなたには「配列」がありません。リストがあります。 Pythonには配列がありますが、それはあなたが使っているものではありません。 – jknupp
@jknupp - あなたはどんなデータ構造ですか?コメントモデル内の「添付ファイル」属性?あなたがcomment_attachments_arrについて話しているのであれば、それは正しくは(申し訳ありませんが)名前が付けられていません - 数字(ID)としてのキーと配列としての値を持つdictです。 – serverman
@jknupp:Python 'list'は配列(またはベクトル)です。リンクされたデータ構造ではありません。これは、ほとんどの人が" list "を読むときに考えるものです。 – Marcin