Reputation: 2136
I am building a web application in python using the django framework. In my application users need to be able to apply for jobs.
I am unsure how to save a list of users who have applied for a job in the job model as a field.
Here is my Job.py
model:
class Job(models.Model):
user = models.ForeignKey(User, related_name="jobs")
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=30)
description = models.TextField()
pay = models.FloatField()
category = models.CharField(max_length=3, choices=JOB_CATEGORY_CHOICES)
#applicants =
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('jobs:detail', kwargs={
'job_pk': self.id
}
)
I need to have the applicants field (which is currently commented out) to store the users who have applied for the job. How do I do this?
Upvotes: 1
Views: 527
Reputation: 3130
If I understand your question correctly, I think you'd need your models set up like this:
class Job(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=30)
description = models.TextField()
pay = models.FloatField()
category = models.CharField(max_length=3, choices=JOB_CATEGORY_CHOICES)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('jobs:detail', kwargs={
'job_pk': self.id
}
)
class Applicant(models.Model):
job = models.ForeignKey(Job, related_name="applicants")
user = models.ForeignKey(User)
This creates a one-to-many relationship from Job
to Applicant
and then a one-to-many relationship from the Applicant
to the User
.
Upvotes: 1
Reputation: 77942
Assuming a user can apply to many jobs and a job can have many users applying, the simple solution is a many to many relationship, defined by a ManyToManyField
:
class Job(models.Model):
users = models.ManyToManyField(User)
Now you may want to keep track of additional informations about the application (date etc), in which case an explicit intermediate model might be handy:
class Application(models.Model):
job = models.ForeignKey(Job)
user = models.ForeignKey(User)
date ⁼ models.DateTimeField(...)
# etc
class Meta:
# you probably don't want the same user
# to apply twice to the same job
unique_together = [("job", "user"),]
Upvotes: 1
Reputation: 478
As themanatuf said, other models with foreign keys and one to one relationships would do the trick.
I would advise you do the Django 101 polls tutorial first though - it is well explained and has very similar related-models architecture than the one you wish to build.
Have fun !
Upvotes: 0