django - 在 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
但必须有更好的方法。
也许有更好的方法来制作这个副本?
解决方案
据我所知:
- 您的 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
推荐阅读
- javascript - 外部 Js 文件中的一项功能未在 HTMLButtonElement.onclick 中定义
- sql - 我们如何在 HAVING 子句中编写带有搜索条件的摘要查询?
- java - 如何将流转换为增强循环
- google-apps-script - Google Apps - 如何从当前目录获取所有文件名?
- mysql - 我无法让我的查询从我的产品表中提取所有记录
- c++ - C++字节数组到int
- python - 如何将frozendict对象转换为熊猫数据框
- javascript - 如何查看 RecyclerView 项目逆序最新项目在顶部
- c# - 如何在 C# 控制台应用程序中使用扩展 ascii 字符
- spring-boot - Spring Boot、H2 和 Flyway:使用两个版本的数据库运行集成测试