如何立即更改 Django 模型中对象的记录?
How to change record of object in Django's model instantly?
我有一个 class 及其对象,我想在保存新记录时,Django 检查 "is_it_true" 是 False 还是 True,如果是 True 则它会更改 "number" 到一个新值,该值对应于具有 "is_it_question" 加一的对象的计数;如果它是 false,"number" 的默认值将保留为默认值 (100)。我该怎么办?
class TypeFourChoice(models.Model):
question_choice = models.ForeignKey(TypeFour)
is_it_question = models.BooleanField(default=False)
number = models.PositiveIntegerField(blank=False, default=100)
word_or_words = models.CharField(default='', blank=False, max_length=20)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "{}".format(self.question_choice)
@classmethod
def save(cls, *args, **kwargs):
no = cls.objects.exclude(number=100).count()
if no is None:
pass
else:
clss = cls.objects.get(???????)
if clss.is_it_question:
no += 1
clss.number = no
clss.save(*args, **kwargs)
else:
clss.number = 100
clss.save(*args, **kwargs)
您应该从 save()
方法中删除 @classmethod
装饰器。并将方法简化为:
def save(self, *args, **kwargs):
# New objects have no `pk`
if self.pk is None and self.is_it_question:
self.number = TypeFourChoice.objects.filter(is_it_question=True) \
.count() + 1
super(TypeFourChoice, self).save(*args, **kwargs)
我有一个 class 及其对象,我想在保存新记录时,Django 检查 "is_it_true" 是 False 还是 True,如果是 True 则它会更改 "number" 到一个新值,该值对应于具有 "is_it_question" 加一的对象的计数;如果它是 false,"number" 的默认值将保留为默认值 (100)。我该怎么办?
class TypeFourChoice(models.Model):
question_choice = models.ForeignKey(TypeFour)
is_it_question = models.BooleanField(default=False)
number = models.PositiveIntegerField(blank=False, default=100)
word_or_words = models.CharField(default='', blank=False, max_length=20)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "{}".format(self.question_choice)
@classmethod
def save(cls, *args, **kwargs):
no = cls.objects.exclude(number=100).count()
if no is None:
pass
else:
clss = cls.objects.get(???????)
if clss.is_it_question:
no += 1
clss.number = no
clss.save(*args, **kwargs)
else:
clss.number = 100
clss.save(*args, **kwargs)
您应该从 save()
方法中删除 @classmethod
装饰器。并将方法简化为:
def save(self, *args, **kwargs):
# New objects have no `pk`
if self.pk is None and self.is_it_question:
self.number = TypeFourChoice.objects.filter(is_it_question=True) \
.count() + 1
super(TypeFourChoice, self).save(*args, **kwargs)