简体   繁体   English

Django:复制和更新查询集

[英]Django: copy and update a queryset

I have the following models:我有以下型号:

class A(models.Model):
    pass

class B(models.Model):
   a = models.ForeignKey(A, related_name="bs")

then I have a function where I create a new record of object A and I would like to copy all the related records of B然后我有一个函数,我创建对象A的新记录,我想复制B所有相关记录

I have done something such as我做过类似的事情

def foo(new_a, old_a):
    old_a.bs.all().update(pk=None, a=new_a)

but I get the following error ERROR - failed to write data to stream: <open file '<stdout>', mode 'w' at 0x7f207949a150>但我收到以下错误ERROR - failed to write data to stream: <open file '<stdout>', mode 'w' at 0x7f207949a150>

Hope that help:希望有帮助:

queryset = B.objects.filter(something="a")

for element in query_set:
    a_object = A.objects.bulk_create(**element)

Doing something like this做这样的事情

def foo(new_a, old_a):
    old_a.bs.all().update(pk=None)

will try to set pk=None on all the bs for old_a which is not what you want.将尝试在所有bsold_a设置pk=None这不是您想要的。

Instead you'll want to do something like:相反,您会想要执行以下操作:

for b in old_a.bs.all():
    b.pk = None # make sure you're not overwriting the existing record
    b.a = new_a
    b.save()

I think you should also be able to use bulk_create to do this more efficiently:我认为您还应该能够使用bulk_create更有效地执行此操作:

new_bs = []
for b in old_a.bs.all():
    b.pk = None # make sure you're not overwriting the existing record
    b.a = new_a
    new_bs.append(b)

B.objects.bulk_create(new_bs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM