Reputation: 2136
I am building a django web app which requires a one to many model relationship. I read the docs and it says to use a ForeignKey
in the model field.
In my case every user needs to have a one to many field with the job model which will keep track of completed jobs by that user.
Which in django I believe is represented like so:
class User(AbstractBaseUser, PermissionsMixin):
...
job_history = models.ForeignKey(Job, on_delete=models.CASCADE)
The job model looks like this:
class Job(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, 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)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('jobs:detail', kwargs={
'job_pk': self.id
}
)
In my view I want to add a job to the job_history
one to many field. I do not know how to write this however. This is my view so far:
@login_required
def job_hire(request, account_pk, job_pk):
user = get_object_or_404(account_pk)
job = get_object_or_404(job_pk)
# I now need to save the job object in the one to many field of the user object. But how?
messages.success(request, "You have hired an applicant.")
return HttpResponseRedirect(reverse('jobs:find'))
How do I add the job to the one to many field in the user model to save the users jobs?
Upvotes: 2
Views: 5809
Reputation: 18972
It is redundant that a User
points to a Job
and a Job
points to a User
as you can follow relationships backward.
The user
field on the Job
should be enough.
You still can lookup all jobs for a User
via:
user = User.objects.first()
user.jobs.all() # shows all jobs for the user.
(Note that it would be user.job_set.all()
if you hadn't set a related name to jobs
)
So in your view this should be enough:
@login_required
def job_hire(request, account_pk, job_pk):
user = get_object_or_404(User, pk=account_pk)
job = get_object_or_404(Job, pk=job_pk)
job.user = user
job.save()
Actually you don't even need to fetch a User-Instance from the database but can do this:
@login_required
def job_hire(request, account_pk, job_pk):
job = get_object_or_404(Job, pk=job_pk)
job.user_id = account_pk
job.save()
Edit:
In case you want to keep both user fields and want to associate a job with a user the mechanics are still the same:
@login_required
def job_hire(request, account_pk, job_pk):
user = get_object_or_404(User, pk=account_pk)
user.job_history_id = job_pk
# or:
# job =get_object_or_404(Job, pk=job_pk)
# user.job_history = job
user.save()
Upvotes: 2
Reputation: 5151
I think it looks good so far. What you'll want to do is first create Job
object.
job=Job(user=..., etc.)
job.save()
Then you add that job to User
object.
user=User(job_history=job, ...)
user.save()
Upvotes: 0