简体   繁体   中英

How to create an instance of a pre-existing model in django?

I want to create a Task execution checklist app in django. Suppose I have a checklist with 3 tasks assigned to it. Now I want to have multiple instances of that same checklist so that at a time multiple user can cross off from their own instance of that checklist.

Say you have a CheckList object with a reverse relationship task_set for the related Task objects and a ForeignKey to the User model named user

check_list = CheckList.objects.get(pk=foo)
# Force execution of the task_set query so that we can copy the objects
tasks = list(check_list.task_set.all())

Now if you have a list of Users that you want to copy this CheckList to

for user in users:
    check_list.pk = None
    check_list.id = None
    check_list.user = user
    check_list.save()  # New record saved to the DB related to the user
    for task in tasks:
        task.pk = None
        task.id = None
        task.check_list = check_list
        task.save()  # New record saved to the DB related to the new check_list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM