fish_ball fish_ball - 6 months ago 11
Python Question

Django: how to change a base object to an alone subclass object?

Now I'm working with python django.

I have derived a Model class from user:

from django.contrib.auth.models import User

class Customer(User):

mobile = models.CharField(max_length=14)

class Meta:
db_table = 'customer_user'


Now comes the question, I have some normal user object, which is not yet a

>>> john = User.objects.get(username='john')
>>> hasattr(john.customer)

Infact the john object has a row in the user table in database, but has no row in the customer table.

I want to change john into a
object, i.e. adding a row of customer, pointing the parent link to the initial user object row.

I tried the following code, but did not work?

>>> Customer.objects.create(user=john, mobile='1234')

Is there any nice way to do the job?


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)


    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.