Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

python - Django: How to switch relations between two objects

I am having issues updating a website I run. Essentially, the users on the website cannot be used anymore, so people have to create new accounts. However, users have ManyToMany relations with other tables in the database, and I want to be able to move the relations from the old users to the new ones.

Is there any good way to do this in Django or directly in the database? I am using PostgreSQL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Django has a management command framework for this. https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/

This should live in PROJECT/APPNAME/management/commands/

from django.core.management import BaseCommand

from django.contrib.auth import get_user_model
User = get_user_model()


#The class must be named Command, and subclass BaseCommand
class Command(BaseCommand):
    # Show this when the user types help
    help = "fix users relations"

    # A command must define handle()
    def handle(self, *args, **options):
        self.stdout.write("fixing users begin")

        for user in User.objects.all():
            ...user fix code...

        self.stdout.write("fix users complete")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...