Home > Mobile >  set user foreign key default value as superuser or admin on on_delete=models.SET_DEFAULT
set user foreign key default value as superuser or admin on on_delete=models.SET_DEFAULT

Time:08-31

As I was using on_delete=models.CASCADE with currentOwner in the asset model, whenever I deleted any user, all the assets owned by that user were getting deleted. I want the asset to be transferred to the superuser/admin. So I tried # MY SOLUTION but it is throwing me an error:

ValueError: Field 'id' expected a number but got 'admin'.

I think deleting previous migrations and running makemigrations and migrate commands might help, but that will probably erase all the data in the database, which I do not want to happen. Here are my User and asset models:

class User(PermissionsMixin, AbstractBaseUser):
    username = models.CharField(max_length=32, unique=True, )
    email = models.EmailField(max_length=32)
    gender_choices = [("M", "Male"), ("F", "Female"), ("O", "Others")]
    gender = models.CharField(choices=gender_choices, default="M", max_length=1)
    nickname = models.CharField(max_length=32, blank=True, null=True)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    REQUIRED_FIELDS = ["email", "gender"]
    USERNAME_FIELD = "username"
    objects = User_manager()

    def __str__(self):
        return self.username

class asset(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=False)
    asset_type = models.ForeignKey('assetType', on_delete=models.CASCADE, null=True)
    asset_name = models.CharField(max_length=30, null=True) #unique=True
    location = models.CharField(max_length=30, null=True)
    brand = models.CharField(max_length=30, null=True)
    purchase_year = models.PositiveIntegerField(blank=True, null=True)
    isActive = models.BooleanField(default=True, null=True)
    currentOwner = models.ForeignKey(User, default=User.objects.get(is_superuser=True).id, null=False, on_delete=models.SET_DEFAULT) # MY SOLUTION

Is there any way this can be solved?

CodePudding user response:

I read documentation here: https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.SET in example you can find your case.

if you don't want to read documentation, the short answer:

For foreign key you should use on_delete=models.SET. AS argument models.SET get a function name.

in your case:

def get_superuser():
    su_user = User.objects.filter(is_superuser=True).first()  # if you have more than 1 superuser, this get the first in list.
    if su_user:
        return su_user
    raise DoesNotExist('Please add Super User')  # or you can create SU here

class asset(models.Model):
    ... # any staff here
    currentOwner = models.ForeignKey(User, on_delete=models.SET(get_superuser))

CodePudding user response:

The solution here was deleting all migrations except the first one, and then running makemigraions and migrate command. Since we never deleted the database, we never lost our records.

  • Related