基于数据库值的Django模型初始表单值

时间:2018-11-05 08:05:14

标签: python django django-models

我有两个模型:

class ReceiptBook(models.Model):
    serial_no = models.IntegerField(unique=True)
    leaf_start = models.IntegerField()
    leaf_end = models.IntegerField()
    issued_person = models.ForeignKey(Person)
    issued_date = models.DateField()
    status = models.CharField(max_length=15,choices=st,default='IS')

class ReceiptLeaf(models.Model):
    receipt_book = models.ForeignKey(ReceiptBook, limit_choices_to={'status': 'IS'})
    receipt_no = models.IntegerField()
    receipt_date = models.DateField()
    received_from = models.CharField(max_length=150)
    kudumba_unit = models.CharField(max_length=20, choices=units)
    amount = models.DecimalField(max_digits=20, decimal_places=2)

在我的管理界面中,我显示 ReceiptLeaf 模型,该模型与 ReceiptBook 内联。现在,我要使用 receipt_book 字段初始化 receipt_no 字段的值,即;使用 receipt_book 对象的 leaf_start leaf_end 的值。 我在admin.py上具有此功能:

def get_receipt_no(self):
    receipt = ReceiptLeaf.objects.filter(receipt_book=?) #how to get receipt book object here
    no = receipt.receipt_no + 1
    if not no:
      no = receipt.receipt_book.leaf_start
    return no

formfield_for_dbfield 方法使用:

def formfield_for_dbfield(self, db_field, **kwargs):
    field =  super(ReceiptLeafInline, self).formfield_for_dbfield(db_field, **kwargs)
    if db_field.name == 'receipt_no':
        field.initial = get_receipt_no(self)
    return field

如何将 receipt_book 的值传递给 get_receipt_no() 函数?由于不止一个ReceiptLeaf与一个ReceiptBook相关联,因此我需要 receipt_book 对象来正确初始化 receipt_no 字段。

0 个答案:

没有答案