Files
Django/jituan/management/commands/backfill_user_club_id.py

54 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""回填用户 ClubID缺省或空时设为 xq 或 user_wx_openid 绑定)。"""
from django.core.management.base import BaseCommand
from django.db import transaction
from jituan.constants import CLUB_ID_DEFAULT
from jituan.models import UserWxOpenid
from users.business_models import User
class Command(BaseCommand):
help = '回填 User.ClubIDOpenID 绑定 → user_wx_openid否则默认 xq'
def add_arguments(self, parser):
parser.add_argument(
'--dry-run',
action='store_true',
help='仅统计不落库',
)
def handle(self, *args, **options):
dry_run = options.get('dry_run', False)
updated = 0
skipped = 0
users = User.query.all()
for user in users:
current = getattr(user, 'ClubID', None) or ''
if current and current != CLUB_ID_DEFAULT:
skipped += 1
continue
new_club = CLUB_ID_DEFAULT
if user.OpenID:
binding = UserWxOpenid.query.filter(openid=user.OpenID).order_by('id').first()
if binding:
new_club = binding.club_id
if current == new_club:
skipped += 1
continue
if dry_run:
self.stdout.write(f'[dry-run] {user.UserUID} -> ClubID={new_club}')
updated += 1
continue
with transaction.atomic():
user.ClubID = new_club
user.save(update_fields=['ClubID'])
updated += 1
suffix = 'dry-run' if dry_run else ''
self.stdout.write(self.style.SUCCESS(f'完成{suffix}:更新 {updated},跳过 {skipped}'))