Alfred Huang
Alfred Huang

Reputation: 18235

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'

Question

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

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

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 Customer 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?

Upvotes: 0

Views: 43

Answers (1)

solarissmoke
solarissmoke

Reputation: 31434

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.

Upvotes: 1

Related Questions