Created
May 11, 2022 13:31
-
-
Save buddylindsey/7cbbc0517237b6aac2b51fcafaceca50 to your computer and use it in GitHub Desktop.
Django: Migrate all of a Users FK and OneToOne fields to another user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any, List, Type, Union | |
from django.apps import apps | |
from django.db import transaction | |
from django.db.models import Model | |
from django.db.models.fields import Field | |
from django.db.models.fields.related import ForeignKey, ForeignObjectRel, OneToOneField | |
class MigrateUser: | |
def __init__(self, _from_id: int, to_id: int) -> None: | |
self._from_id = _from_id | |
self.to_id = to_id | |
self._from: User = User.objects.get(id=_from_id) | |
self.to: User = User.objects.get(id=to_id) | |
def run(self) -> None: | |
with transaction.atomic(): | |
for model in self.get_models_to_migrate(): | |
model_fields = self.get_foreign_key_and_one_to_one_related_fields(model) | |
self.update_model_based_on_fields(model, model_fields) | |
def get_models_to_migrate(self) -> List[Type[Model]]: | |
return apps.get_models() | |
def is_user_related_field(self, field: Union[Field[Any, Any], ForeignObjectRel]) -> bool: | |
""" | |
Check if the relationship is either a FK or 1-to-1 as they act the same | |
""" | |
return field.__class__ in [ForeignKey, OneToOneField] and field.related_model == User | |
def get_foreign_key_and_one_to_one_related_fields(self, model: Type[Model]) -> List[str]: | |
return [field.name for field in model._meta.get_fields() if self.is_user_related_field(field)] | |
def update_model_based_on_fields(self, model: Type[Model], model_fields: List[str]) -> None: | |
for field_name in model_fields: | |
# get all records based on the field for the old user | |
filters = {field_name: self._from_id} | |
results = model.objects.filter(**filters) | |
# update all of the records we just got to the new user | |
results.update(**{field_name: self.to_id}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment