我有以下型号:
class Vehicle(models.Model):
name = models.CharField(max_length=180, verbose_name='Nazwa')
variant = models.IntegerField(default=0)
route = models.ForeignKey(Route)
active = models.BooleanField(default=True)
class Meta:
unique_together = ("name", "variant")
def save(self, *args, **kwargs):
vehicles = Vehicle.objects.filter(name=self.name).order_by('-variant')
try:
self.variant = vehicles[0].variant+1
except:
pass
super(Vehicle, self).save(*args, **kwargs)
问题是,当我创建新对象时,该名称不会出现在数据库中,它会创建variant = 1
而不是default 0
的对象。当我创建另一个具有相同名称的对象variant is incremented by 2 instead of 1
时
因此,当我创建具有相同名称的多个对象时,variants
仅以奇数进行,e.g.: 1,3,5,7,9,11...
我的模特出了什么问题?
答案 0 :(得分:1)
代码出错:您之前未检查此模型是否已保存。测试用例:
vehicle = models.Vehicle(name='Foo')
vehicle.save() #variant==0 by default
Vehicle.active = False
vehicle.save() #there is already a record with this name. Increment variant anyway
这种方法对我来说更好看:
def save(self, *args, **kwargs):
if self.id is None: #works only when saved first time
self.variant = Vehicle.objects.filter(name=self.name).count()
super(Vehicle, self).save(*args, **kwargs)