我有一个模型定义为-
class sales_order(models.Model):
customer=models.ForeignKey()
item=models.ForeignKey()
branch=models.ForeignKey()
---
---other fields
现在对于每个分支,我想从1 ("id"),但Django的默认功能是不管其他数据如何,都会自增id。
我可以即使id继续递增,然后我设置我自己的字段,使其每个分支唯一,这个字段应该自动递增,而不需要用户通过检查数据库中的前一个值来传递数据,如-
class order_serializer(serializers.ModelSerializer):
class Meta:
validators = [
UniqueTogetherValidator(
queryset=sales_order.objects.all(),
fields=['myOwnDefinedField', 'branch']
)
]
我不知道如何做到这一点。使用Django 3.1.5.
帮忙吗?
在模型的save
方法中,您可以执行查询以获取当前分支字段中的最大值,将该值添加1,然后将其保存为新值。只有在没有值的情况下才这样做,这样我们就不会覆盖现有的行
使用元。unique_together在DB级别也强制此约束
from django.db.models.functions import Coalesce
class SalesOrder(models.Model):
branch = models.ForeignKey(Branch, on_delete=models.CASCADE)
branch_unique_id = models.IntegerField(editable=False, blank=True)
class Meta:
unique_together = (
('branch', 'branch_unique_id'),
)
def save(self, *args, **kwargs):
if not self.branch_unique_id:
self.branch_unique_id = SalesOrder.objects.filter(
branch=self.branch
).aggregate(
max=Coalesce(models.Max('branch_unique_id'), 0)
)['max'] + 1
super().save(*args, **kwargs)