如何在django中添加一对多的关系对象? [英] How to add object to a one to many relationship in django?

查看:138
本文介绍了如何在django中添加一对多的关系对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个需要一对多模型关系的django网络应用程序。我阅读了文档,并且在模型字段中使用了一个 ForeignKey

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.

在django中,我认为这样表示如下:

Which in django I believe is represented like so:

class User(AbstractBaseUser, PermissionsMixin):
    ...
    job_history = models.ForeignKey(Job, on_delete=models.CASCADE)

作业模型如下所示:

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

在我看来,我想将一个工作添加到 job_history 一对多的字段中。我不知道如何写这个。这是我到目前为止的观点:

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?

推荐答案

多余的用户指向作业作业指向用户,您可以后跟关系

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. 

(请注意,这将是 user.job_set.all() code>如果您没有将相关名称设置为 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()






编辑:


如果你想保持两者用户字段,并希望将作业与用户的机械师关联他相同:

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

这篇关于如何在django中添加一对多的关系对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆