复制一条既存的数据,作成多条新数据
pl = Pl.objects.get(pk=1) # 找一条数据
npl=pl # 复制
npl.pk=None # 主键清空
npl.save() # 保存一个新的对象parent model:Product
child model:ProductList
给每一个Product做一条ProductList数据
>>> from .models import ProductList, Product
>>> pl = ProductList.objects.get(pk=1) # 复制一条数据
>>> products = Product.objects.all() # product为productlist 的外键
>>> for p in products:
... newpl=ProductList()
... newpl=pl # 复制
... newpl.product = p # 登录外键
... newpl.pk=None # 主键清空 ,若不清空主键,newpl与pl指向同一地址,每次loop只会更新pl
... newpl.save()
>>> model参照
class ProductList(BaseModel):
product = models.ForeignKey(Product, verbose_name='商品', on_delete=models.SET_NULL, null=True)
code = models.CharField(verbose_name='コード', max_length=20, default="")原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。