【问题标题】:Avoid Django def post duplicating on save避免 Django def post 在保存时重复
【发布时间】:2014-12-23 21:23:33
【问题描述】:

您好,我在保存时遇到了重复对象的问题。 我怎样才能防止这种情况?

提前致谢。

#models.py
class Candidate(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    birth = models.CharField(max_length=50)
     ...

class Job(models.Model):
    candidate = models.ManyToManyField('Candidate', through='CandidateToJob')
    title = models.CharField(max_length=500)
    ...

class CandidateToJob(models.Model):
    job = models.ForeignKey(Job, related_name='applied_to')
    candidate = models.ForeignKey(Candidate, related_name='from_user')
    STATUS_CHOICES = (
       ('1', 'Not approved'),
       ('2', 'Approved'),
       ('3', 'Hired')
    )
    status = models.CharField(max_length=2, choices=STATUS_CHOICES)

    class Meta:
        unique_together = ("candidate", "job")

这里是风景

#views.py
class JobDetails(generic.DetailView):

model = Job
template_name = 'companies/job-detail.html'
form_class = ApplyForm

def get_context_data(self, **kwargs):
    context = super(JobDetails, self).get_context_data(**kwargs)
    context['company_detail'] = Company.objects.all()
    return context

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    messages.success(request, 'Sucesso!')

    if form.is_valid():
        form.save(commit=False)
        #create job
        job = self.get_object(queryset=Job.objects.all())
        #create candidate
        candidate = Candidate.objects.get(pk=request.user)

        #assign to the through table
        candidatetojob = CandidateToJob.objects.create(job=job, candidate=candidate)

        candidatetojob.save()

    return HttpResponseRedirect('/jobs/')

还有形式

#forms.py
class ApplyForm(ModelForm):

class Meta:
    model = CandidateToJob
    exclude = ['candidate', 'job', 'status']

尽管有 unique_together,但该函数始终保存复制它们的对象。

【问题讨论】:

  • 您为什么使用 DetailView 而不是某种形式的视图 - 例如 UpdateView?
  • 你好丹尼尔。我正在使用它,因为我想展示一个特定的工作及其详细信息。您认为在这种情况下使用 updateview 更好吗?我的意思是,即使我使用 updateview,post 方法也会不断重复条目。

标签: django django-views has-many-through m2m


【解决方案1】:

我让它工作了。这是我的代码:

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)

    #create job
    job = self.get_object(queryset=Job.objects.all())

    #create candidate
    candidate = Candidate.objects.get(pk=request.user)

    #check if objects exists before save
    if CandidateToJob.objects.filter(job = job, candidate = candidate).exists():

        messages.error(request, 'You have applied already for this position')

        return HttpResponseRedirect(reverse('jobdetail', kwargs={'pk': job.pk}))

    else:

        if form.is_valid():
            form.save(commit=False)

            #assign to the through table
            candidatetojob = CandidateToJob.objects.create(job=job, candidate=candidate, status='0')

            candidatetojob.save()

            messages.success(request, 'Success! Good luck.')

    return HttpResponseRedirect('/jobs/')

【讨论】:

  • 这不会将您从竞争条件中解救出来。最好用atomic() 包装它
猜你喜欢
  • 2011-08-25
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2013-02-16
  • 2020-05-18
  • 2011-03-04
  • 2019-10-18
相关资源
最近更新 更多