首页 > 解决方案 > 在 django 中使用外键复制数据库的一部分

问题描述

我每年都有许多对象,并希望使用适当的外键将其中一个复制到新的一年。下面的模型实现链接到许多时刻,当我制作新副本时,我想“保持”新时刻和新实现之间的联系。

根据我在 Internet 上找到的内容,我正在编写以下代码:

realis_lista = Realisering.objects.filter(year=thisyear).all()
for obj in realis_lista:
    new_obj = obj
    moment = Moment.objects.filter(realisering__pk=obj.pk).all()
    new_obj.pk = None
    new_obj.year = nextyear
    new_obj.save()

    if moment:
        for mom in moment:
            new_mom = mom
            new_mom.pk = None
            new_mom.realisation = ??new_obj??

最后一行应该是什么?我需要找到 new_obj 的保存位置(它的 pk),但我唯一的想法是使用类似的东西

n_obj = 
Realisering.objects.filter(year=nextyear).filter(period=obj.period)....    
new_mom.realisation=n_obj 

但必须有更好的方法。

也许有更好的方法来制作这个副本?

标签: django

解决方案


据我所知:

  • 您的 Moment 模型具有实现模型的外键。
  • 您从这一年中获取所有实现,thisyear并为每个实现创建一个副本,并带有新的一年nextyear
  • 对于每个实现,您制作与其关联的 Moment 的副本(如果有),并且您希望将 Realization 的新年副本分配给该 Moment 的副本。

据我所知,您无需搜索new_obj保存的位置,您已经在代码中找到了它。

我觉得你应该试试

for obj in Realisering.objects.filter(year=thisyear).all():
    # .first() will return None if it doesn't find it
    moment = Moment.objects.filter(realisering__pk=obj.pk).first() 
    obj.year = nextyear
    # The my_object.pk = None and my_object.save() combinaison will generate a new instance
    obj.pk = None
    obj.save()
    # obj is now the copy of the object

    if moment:
        moment.pk = None
        # We assign the Realisation copy to the Moment copy
        moment.realisation = obj
        moment.save()

请注意,如果您的模型使用继承、ManyToMany 字段或 OneToOne 字段,则必须采取额外的预防措施:https ://docs.djangoproject.com/en/2.0/topics/db/queries/#copying-model-instances


推荐阅读