[Fixed]-Django: how to change a base object to an alone subclass object?

1👍

You have two options, as described in the documentation:

1. Make your Customer model a proxy for the User model:

class Customer(User):

    class Meta:
        proxy = True

Then any instance of User is also an instance of Customer. Note that you probably don’t want to set a custom table_name in this case because both models operate through the same table.

2. Make your Customer a profile model that has a one-to-one relationship with the core User model:

from django.contrib.auth.models import User

    class Customer(models.Model):

        user = models.OneToOneField(User, on_delete=models.CASCADE)
        mobile = models.CharField(max_length=14)

Then:

john = User.objects.get(username='john')
if not hasattr(john, 'customer'):
    Customer.objects.create(user=john, mobile='1234')

The second approach seems to me to be a better fit for your use case.

Leave a comment