有没有办法相对于前一个字段自动增加一个字段...例如,如果前一个记录的值是 09-0001,那么下一个记录应该分配 09-0002 等等...想法?我正在考虑覆盖保存方法,但我不太确定
Stephen
问问题
16983 次
3 回答
10
Django 不会让您在模型中拥有多个 AutoField,并且您已经拥有一个作为主键。因此,您必须覆盖 save 并且可能需要回顾表格以找出要增加的内容。
像这样的东西:
class Product(models.Model):
code = models.IntegerField()
number = models.IntegerField()
...
def get_serial_number(self):
"Get formatted value of serial number"
return "%.2d-%.3d" % (self.code, self.product)
def save(self):
"Get last value of Code and Number from database, and increment before save"
top = Product.objects.order_by('-code','-number')[0]
self.code = top.code + 1
self.number = top.number + 1
super(Product, self).save()
# etc.
请注意,如果您的保存方法中没有某种锁定,您可能会遇到并发问题(两个线程试图在代码和数字中存储相同的值)。
于 2009-06-30T20:28:54.610 回答
1
AutoField is the field type that Django uses for the model base class' 'id' property, but you can use it for additional autoincremented fields.
I don't think you can do any formatting like in your example, but a good approach would be to make a custom field type that overrides the save() method to perform the desired formatting.
于 2009-06-30T18:12:33.933 回答
1
在 SQL 中:
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| code | int(11) unsigned | NO | PRI | NULL | auto_increment |
+-------+------------------+------+-----+---------+----------------+
在 Django 中:
self.code = None
self.number = top.number + 1
self.save() # or super(Product, self).save()
保存后code
会自动增加。
于 2013-01-17T03:28:02.593 回答