im having a two models one is companyusers and the other is qualification
and one user has many qualifications
now i need to enter qualifications while creating the user in admin how do i do that?
i have tried to keep many to many field in the users model but in vain... the qualifications that are related to other user is populating in the fields where as i need to create new qualification for the new user.
code follows..
class Qualification(models.Model):
qualification = models.CharField(max_length=250)
max_marks = models.IntegerField(max_length=50)
marks_obtained = models.IntegerField(max_length=50)
qualifying_year = models.DateField(auto_now=False, null=True)
class CompanyUser(User):
date_of_birth = models.DateField(auto_now=False, null=True)
position = models.CharField(max_length=100)
qualifications = models.ManyToManyField(Qualification)
here is the company user details..
{"username":"steve","position":"Senior Engineer", "date_of_birth": "1986-05-14"}
{"qualification":"secondary school", "max_marks":"1000", "marks_obtained":"850", "qualifying_year":"1990"}
{"qualification":"undergraduation", "max_marks":"750", "marks_obtained":"680", "qualifying_year":"1992"}
{"qualification":"postgraduation", "max_marks":"1500", "marks_obtained":"1280", "qualifying_year":"1997"}
The One-To-Many relation you are looking for doesn't exist in Django. It's not needed, since you can do it the other way round: With a ForeignKey relation from the qualification to the user. According to your example, you would define the models as follows:
class Qualification(models.Model):
qualification = models.CharField(max_length=250)
max_marks = models.IntegerField(max_length=50)
marks_obtained = models.IntegerField(max_length=50)
qualifying_year = models.DateField(auto_now=False, null=True)
user = models.ForeignKey('CompanyUser', related_name='qualifications')
class CompanyUser(User):
date_of_birth = models.DateField(auto_now=False, null=True)
position = models.CharField(max_length=100)
So, there is no relation specified from CompanyUser to Qualification but you have a ForeignKey relation from Qualification to CompanyUser (i.e. each qualification belongs to one user, but multiple qualifications can belong to the same user). Django automatically maintains the backwards relation from CompanyUser to Qualification, which is the One-To-Many relation you are looking for. By the option related_name
of the ForeignKey you can specify a meaningful name for the backwards relation (in this case 'qualifications'). You can now simply access the Qualifications on a CompanyUser object with the attribute user.qualifications
.
In the admin you would first create a new CompanyUser and then an arbitrary number of Qualifications which you assign to this user via the ForeignKey.
Be sure to read about that stuff in the Django docs section about Model relationships.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With