如何在django中删除一行时重置id?

lf5gs5x2  于 2022-12-14  发布在  Go
关注(0)|答案(2)|浏览(544)

我想从1开始id。每当删除一行时,它会跳过该数字并跳到下一个数字。x1c 0d1x
就像这幅图,它跳过了1-6和8。
我想把它设置为1,2,3
这是我的models.py

class dish(models.Model):
id = models.AutoField(primary_key=True)      
dish_id = models.AutoField
dish_name = models.CharField(max_length=255, blank=True, null=True)
dish_category = models.CharField(max_length=255, blank=True, null=True)
dish_size = models.CharField(max_length=7, blank=True, null=True)
dish_price = models.IntegerField(blank=True, null=True)
dish_description = models.CharField(max_length=255, blank=True, null=True)
# dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
dish_date = models.DateField()

def __str__(self):
    return self.dish_name

这是views.py

def delete(request, id):
dishs = dish.objects.get(id=id)
dishs.delete()
return HttpResponseRedirect(reverse('check'))
oxalkeyp

oxalkeyp1#

删除一个对象并不会更改其余对象的任何属性。您需要手动执行此操作。您需要做的第一件事是更改dish_id字段:

# Change this:
# dish_id = models.AutoField
# to this:
dish_id = models.IntegerField(default=0)

然后在你看来:

def delete(request, id):
    dishs = dish.objects.get(id=id)
    dishs.delete()

    all_dishes = dish.objects.all()
    for i, dish in enumerate(all_dishes):
        dish.dish_id = i + 1
        dish.save()
    
    return HttpResponseRedirect(reverse('check'))

另外,你真的应该用Pascal大小写来写你的类,大写类的第一个字母:

class Dish(models.Model):

最后,Dish不需要ID字段;这是自动创建的,但您可以保持原样,它不会导致任何问题。

plicqrtu

plicqrtu2#

您可以使用覆盖保存()方法来实现这些功能,如下所示

class dish(models.Model):
    id =models.AutoField(primary_key=True)      
    dish_id = models.BigIntegerField(unique = True)
    dish_name = models.CharField(max_length=255, blank=True, null=True)
    dish_category = models.CharField(max_length=255, blank=True, null=True)
    dish_size = models.CharField(max_length=7, blank=True, null=True)
    dish_price = models.IntegerField(blank=True, null=True)
    dish_description = models.CharField(max_length=255, blank=True, null=True)
    dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
    dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
    dish_date = models.DateField()
        
    def __str__(self):
        return self.dish_name

    def save(self, *args, **kwargs):
        count_obj = dish.objects.all().count()+1
        self.dish_id = count_obj
        super(dish, self).save(*args, **kwargs)

相关问题