英文:
Django ORM create model object using another object
问题
我想要做类似以下的操作来在另一个数据库中创建对象:
my_model.objects.using('DB2').create(my_model=get_object)
英文:
How can we create a model record or object using another object.
get_object = my_model.objects.filter(id=1)
I want to do something like below to create object in another database
my_model.objects.using('DB2').create(my_model=get_object)
答案1
得分: 0
你可以覆盖save方法或使用django signals,根据你的需求。
你可以使用以下代码将对象复制到另一个具有相同字段的数据库模型中。
get_object = my_model.objects.filter(id=1).values().first()
get_object.update({'id': None})
my_model.objects.using('DB2').create(**get_object)
英文:
You can overide save method or use django signals, based on your requirements.
You can use the code below to replicate the object to the model in another database having same fields.
get_object = my_model.objects.filter(id=1).values().first()
get_object.update({'id': None})
my_model.objects.using('DB2').create(**get_object)
答案2
得分: 0
你可以将你的模型作为字典获取,并解包到新的模型对象中。
from users.models import User, AnotherUser
from django.forms.models import model_to_dict
old_user = User.objects.get(pk=1)
data = model_to_dict(old_user, fields=['username', 'email'])
new_user = AnotherUser.objects.using('DB2').create(**data)
最好不要复制主键(id),而是让数据库自己提供它。
英文:
You can get yours model as dict and unpack it to new model object.
from users.models import User, AnotherUser
from django.forms.models import model_to_dict
old_user = User.objects.get(pk=1)
data = model_to_dict(old_user, fields=['username', 'email'])
new_user = AnotherUser.objects.using('DB2').create(**data)
Its better to not copy pk(id) but provide this to database by itself
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论