Answer the question
In order to leave comments, you need to log in
How in Django to keep the fields of only the child model, and not affect the fields of the parent model?
I have an application "profile" and two models: "Human" and "Client".
The "Human" model extends the built-in "User" model.
And the "Client" model extends the "Human" model.
from django.contrib.auth.models import User
class Human(User):
city = models.CharField(max_length=100, blank=True)
address = models.CharField(max_length=150, blank=True)
phone = models.CharField(max_length=30, blank=True)
def __str__(self):
return "{0} ({1})".format(self.username, self.get_full_name())
class Client(Human):
company = models.CharField(max_length=100, blank=True)
discount = models.DecimalField(max_digits=4, decimal_places=2, default=15)
def __str__(self):
return "#{} : {} | {} ({})".format(self.id, self.username, self.get_full_name(), self.company)
from profile.models import Human
hu = Human(username='first', email='[email protected]', first_name='Mr.First', city='First City', phone="+9876543210")
hu.set_password('12345678')
hu.save()
from profile.models import Client
cli = Client(id=3, company='FST', discount=10.00)
cli.update()
cli.save(update_fields=['company', 'discount'])
cli.save()
Answer the question
In order to leave comments, you need to log in
What I love about Django is that it's very convenient. It turns out the solution was very simple. It is a pity that I could not find it in the official documentation (in my opinion the documentation is poorly done).
To put it simply, the solution would be:
from profile.models import Client
cli = Client(company = 'FST', discount=10.00, human_ptr_id=3)
cli.save_base(raw = True)
1. Inheriting from This is VERY bad practice. Don't do it. The User model is not an abstract model.
2. You have three different models, hence three different tables. There is no connection between them.
3. The correct solution would be to override the User model. Here is a tutorial for this https://simpleisbetterthancomplex.com/tutorial/201... The
fourth option will work for you. Then you can get rid of Human.
And connect the Client model with the User via ForeignKeyfrom django.contrib.auth.models import User
class CustomUser(AbstractBaseUser, PermissionsMixin):
# some fields
# some methods
class Client(models.Model):
user = models.ForeignKey("CustomUser", on_delete=models.CASCADE)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question