gpt4 book ai didi

python - 如何在 get_or_create 中用另一个对象更新对象?

转载 作者:行者123 更新时间:2023-11-29 03:33:15 29 4
gpt4 key购买 nike

我必须使用具有相似字段的表,并且我想将对象从一个表复制到另一个表。第二个表中可能没有对象的问题,所以我必须使用 get_or_create() 方法:

#these are new products, they all are instances of NewProduct model, which is similar
#to Product model
new_products_list = [<NewProduct: EEEF0AP>, <NewProduct: XR3D-F>,<Product: XXID-F>]

#loop over them and check if they are already in database
for product in new_products_list:
product, created = Products.objects.get_or_create(article=product.article)

if created:
#here is no problem because new object saved
pass
else:
# here I need to code that will update existing Product instance
# with values from NewProduct instance fields

情况是我不想像这样手动列出所有要更新的字段,因为我有大约 30 个字段:

update_old_product = Product(name=new_product.name,article= new_product.article)

请指教比上面更优雅的方式

最佳答案

您可以遍历字段名称并在另一个 Product 实例中更新它们:

for new_product in new_products_list:
# use different variable names, otherwise you won't be able to access
# the item from new_product_list here
product, created = Products.objects.get_or_create(article=new_product.article)

if not created:
for field in new_product._meta.get_all_field_names():
setattr(product, field, getattr(new_product, field))
product.save()

关于python - 如何在 get_or_create 中用另一个对象更新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27362553/

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