gpt4 book ai didi

python - UpdateOrCreate 建立一对多关系

转载 作者:行者123 更新时间:2023-12-01 06:24:21 27 4
gpt4 key购买 nike

已更新

我正在尝试在父表上应用update_or_create方法。然后在 child table 上。但是,当 update_or_create 方法在子级上运行时,会返回此错误...

save() prohibited to prevent data loss due to unsaved related object 'atom_presance'.

看起来子进程不知道父进程的update_or_create并且无法获取foreign_key。

for i, fee in enumerate(fees):
for j, item in enumerate(fee):
projects = AtomPresance() #parent
advertisements = Advertisements() #child

project_name = {'project_name': item["title"]}

kind = item["kind"]
removed_price = {'removed_price': item[kind], "atom_presance":projects} #sending FOREIGN_KEY also

obj, created = AtomPresance.objects.update_or_create(project_name=item["title"], defaults=project_name)
obj, created = Advertisements.objects.update_or_create(saved_date=date, defaults=removed_price)

在这种情况下,在父级和子级上使用 update_or_create 的最佳方法是什么。

最佳答案

当您在默认值中使用update_or_create第二种方法将removed_price分配为第一次创建后放置的字典时,我收到错误AtomPresance 对象并在 removed_price 字典的 atom_presance=obj 中分配键值

you have must pass the reference of parentmodel in childmodel creation replace below code with your code

for i, fee in enumerate(fees):
for j, item in enumerate(fee):
project_name = {'project_name': item["title"]}

kind = item["kind"]

obj, created = AtomPresance.objects.update_or_create(project_name=item["title"], defaults=project_name)

removed_price = {'removed_price': item[kind], "atom_presance":obj} #here change you need to assign the created obj that we create in above line

obj, created = Advertisements.objects.update_or_create(saved_date=date, defaults=removed_price)

关于python - UpdateOrCreate 建立一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60236989/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com