Django:使用信号保存ManyToMany字段 [英] Django: Using signals to save a ManyToMany field
问题描述
我正在尝试将一个ManyToMany字段保存在模型中。由于对象不存在,所以在save()方法中不可能这样做。所以我试着把逻辑放在一个信号中。我的问题是:每当我创建一个新的FaculteAdmissions对象时,信号似乎都会发射两次。主要症状是信号输出复制。这是代码,这将会更明显。
I am trying to save a ManyToMany field post save in a model. It's not possible to do so in the save() method as the object does not exist. So I tried putting the logic in a signal instead. My problem is: the signal seems to fire twice everytime I create a new FaculteAdmissions object. The main symptom is that the signal output is duplicated. Here is the code, it'll be a bit more obvious.
型号:
class FaculteAdmissions(models.Model):
trimestre = models.IntegerField(unique=True)
session = models.CharField(max_length=25)
annee = models.CharField(max_length=10)
date_lecture = models.DateField()
data = models.ManyToManyField(Admissions)
def save(self, *args, **kwargs):
"""
Exécuté avant la sauvegarde d'un objet de ce modèle.
Validera si dans la table Admissions il existe des données pour ce trimestre.
"""
# valide l'unicité
if FaculteAdmissions.objects.filter(trimestre=self.trimestre).exists():
raise ValidationError("Un objet ayant ces valeurs existe déjà")
else:
# valide les données
q = Admissions.objects.filter(trimestre=self.trimestre,
niveau=constantes.NIVEAUX_LECTURE_BD[2])
if not q.exists():
raise ValidationError("Données introuvables dans la table Admissions")
# OK!
super(FaculteAdmissions, self).save(*args, **kwargs)
# Envoie signal pour mettre à jour les données
post_save.send(sender=self.__class__, instance=self, created=True)
def __str__(self):
return "Faculté - Admissions"
关联信号:
def creation_faculte_admissions(sender, instance, created, **kwargs):
if created:
# valide les données
q = Admissions.objects.filter(trimestre=instance.trimestre,
niveau=constantes.NIVEAUX_LECTURE_BD[2])
instance.data = q
print("Données ajouté pour " + str(instance) + str(instance.trimestre))
和信号连接:
post_save.connect(creation_faculte_admissions, sender=FaculteAdmissions, dispatch_uid="faculte_admissions")
推荐答案
正如@karthikr所说,正确的使用信号是 m2m_changed
。
As @karthikr mentionned, the correct signal to use is m2m_changed
.
只需从 post_save
切换到该信号即可。
Simply switching to that signal from post_save
did the trick.
这篇关于Django:使用信号保存ManyToMany字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!