简体   繁体   中英

How to add object to a one to many relationship in django?

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?

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM