无法使用F表达式保存模型

时间:2015-07-31 21:51:51

标签: django python-3.4

我正在使用 F表达式来更新我的一些模型字段。 我想使用特定的自定义模型方法来实现它,但它不起作用。

这是我的模特

class SingletonModel(models.Model):

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        self.__class__.objects.exclude(pk=self.pk).delete()
        super().save(*args, **kwargs)

    @classmethod
    def load(cls):
        try:
            return cls.objects.get()
        except cls.DoesNotExist:
            return cls()

class Folios(SingletonModel):
    _folios = models.PositiveIntegerField(default=0, db_column='folios')
    fecha_ultima_compra = models.DateTimeField()
    fecha_ultima_venta = models.DateTimeField()

    def agregar_folios(self, valor):
        self.fecha_ultima_compra = timezone.now()
        self._folios=models.F('folios') + valor
        self.save()

    def sustraer_folios(self, valor):
        self.fecha_ultimo_venta = timezone.now()
        self._folios=models.F('folios') - valor
        self.save()

当我做的时候

f = Folios.load()
f.agregar_folios(200)

我得到了追溯

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  ... Some more info
    return int(value)
TypeError: int() argument must be a string or a number, not 'CombinedExpression'

1 个答案:

答案 0 :(得分:0)

我解决了,我必须检查db first中是否存在现有记录

def agregar_folios(self, valor):
    self.fecha_ultima_compra = timezone.now()
    if self.pk is not None:
        self._folios = models.F('folios') + valor
    else:
        self._folios = valor
    self.save()

def sustraer_folios(self, valor):
    self.fecha_ultimo_venta = timezone.now()
    if self.pk is not None:
        self._folios = models.F('folios') - valor
    else:
        self._folios = valor
    self.save()