gpt4 book ai didi

python - Django模型在创建后保存了两次

转载 作者:行者123 更新时间:2023-11-28 18:30:49 24 4
gpt4 key购买 nike

我不知道我的模型是如何被保存两次的。该模型称为 Job。如果客户创建订单,则创建 Job 实例。创建后,会有一个信号提醒管理员新的 Job 对象已创建或编辑。

@receiver(post_save,sender=Job)
def alert_admin(sender,instance,created,**kwargs):
if created:
email.AdminNotifications.new_order(instance)
else:
email.AdminNotifications.edited_order(instance)

编辑: 我已经找出导致问题的原因,这是一个信号(问题的最底部)。但是,我确实需要这个信号,所以我仍然不知道如何让它工作......

问题是 AdminUser 创建了一个 Job 之后收到了两封电子邮件。一封电子邮件是订单已创建,第二封电子邮件告知订单已被编辑。

我怀疑这是因为我重写了 saveinit 方法,以创建类似 signal 的东西,当 Job 属性 - approved 已更改。我在这里找到了这个建议 SO QUESTION这是因为在创建一个 Job 之后,管理员必须批准它 - 只需更改 Jobapproved 属性的 Bool 值目的。

我正在附加 view,其中创建了 Job 和模型 Job

View :

def create_order(request):
LanguageLevelFormSet = formset_factory(LanguageLevelForm, extra=5, max_num=5)
language_level_formset = LanguageLevelFormSet(request.POST or None)
job_creation_form = JobCreationForm(request.POST or None, request.FILES or None)

context = {'job_creation_form': job_creation_form,
'formset': language_level_formset}

if request.method == 'POST':
if job_creation_form.is_valid() and language_level_formset.is_valid():
cleaned_data_job_creation_form = job_creation_form.cleaned_data
cleaned_data_language_level_formset = language_level_formset.cleaned_data
for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
language = language_level_form['language']
level = language_level_form['level']
Job.objects.create(
customer=request.user,
text_to_translate=cleaned_data_job_creation_form['text_to_translate'],
file=cleaned_data_job_creation_form['file'],
short_description=cleaned_data_job_creation_form['short_description'],
notes=cleaned_data_job_creation_form['notes'],
language_from=cleaned_data_job_creation_form['language_from'],
language_to=language,
level=level,
)

return HttpResponseRedirect('/order-success')
else:
return render(request, 'auth/jobs/create-job.html', context=context)

return render(request, 'auth/jobs/create-job.html', context=context)

工作:

class Job(models.Model):
customer = models.ForeignKey(User, related_name='orders', help_text=_("Customer"), on_delete=models.CASCADE)
translator = models.ForeignKey(User, related_name='jobs', null=True, blank=True, help_text=_(u"Translator"))
price = models.FloatField(null=True, blank=True, help_text=_(u"Price"))
language_from = models.ForeignKey(Language, related_name='jobs_from', null=True)
language_to = models.ForeignKey(Language, related_name='jobs_to', null=True)
short_description = models.CharField(max_length=40, blank=False,
help_text=_(u"Very short description of this order"))
notes = models.TextField(help_text=_("Notes"))
text_to_translate = models.TextField(verbose_name='Text to translate', blank=True, null=True,
help_text=u"Text, ktorý chcete preložiť (ak neprikladáte súbor).")
file = models.FileField(null=True, blank=True, help_text=u"Upload file")
level = models.ForeignKey(Level, null=False, default=None)
delivery_date = models.DateField(null=True, blank=True, help_text=_('Deadline'))

PROGRESS_CHOICES = (

('translator_not_assigned_yet', 'Translator not assigned yet'),
('in_translation_process', 'In translation process'),
('translated', 'Translated'),
('complete', 'Complete')
)
progress = models.CharField(choices=PROGRESS_CHOICES, max_length=40, default='translator_not_assigned_yet')
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=False)
is_done = models.BooleanField(default=False)

approved = models.BooleanField(default=False)
__original_approved = None

def __init__(self, *args, **kwargs):
super(Job, self).__init__(*args, **kwargs)
self.__original_approved = self.approved

def save(self, force_insert=False, force_update=False, *args, **kwargs):
if self.approved != self.__original_approved and self.approved == True:
send_job_alert(self)
else:
pass
super(Job, self).save(force_insert, force_update, *args, **kwargs)
self.__original_approved = self.approved

@staticmethod
def get_approved_pending_jobs():
approved_pending_jobs = Job.objects.filter(approved=True, delivery__status='pending')
return approved_pending_jobs

@staticmethod
def get_open_jobs_for_user(user):
results = set()
candidate_jobs = Job.objects.filter(language_from__in=user.userprofile.languages_verified,
language_to__in=user.userprofile.languages_verified,
delivery__status='pending',
).exclude(customer=user)

for job in candidate_jobs:
if job.level.name <= user.userprofile.language_levels.get(language=job.language_to).level.name:
results.add(job)
return list(results)

@property
def has_translator(self):
return self.translator_id is not None

传递信号:

@receiver(post_save,sender=Job)
def create_delivery(sender,instance,created,**kwargs):
if created:
delivery,created_delivery = Delivery.objects.get_or_create(job=instance)
instance.delivery = delivery
delivery.save()
instance.save()

最佳答案

在根据 docs 连接接收器时添加 dispatch_uuid

def create_delivery(sender, instance, created, **kwargs):
if created:
delivery,created_delivery = Delivery.objects.get_or_create(job=instance)
instance.delivery = delivery
delivery.save()
instance.save()

post_save.connect(create_delivery, sender=Job, dispatch_uid="my_unique_identifier")

关于python - Django模型在创建后保存了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37621106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com