2014-03-29 118 views
0

我有以下模型:独特的价值问题

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

因为你正在做的'车[0] .variant + 1' __and__'超(车辆,个体经营).save(.. 。。保存命令被调用两次,所以'variant'增加两次 – sshashank124

回答

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)