根据外键在相关模型中插入值

时间:2016-08-29 09:38:48

标签: django django-models

我试图通过表单将相关的值插入到多个模型中。我有一些困难。

我有三个相关的模型:

class Member(models.Model):
    member_id = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=50, default='test first name')
    last_name = models.CharField(max_length=50, default='test last name')

class Loans (models.Model):
    loan_id = models.AutoField(primary_key = True)
    member = models.ForeignKey('Member',related_name='loans')

class Transactions (models.Model):
    transaction_id = models.AutoField(primary_key=True)
    amount = models.DecimalField(max_digits = 10, decimal_places = 2)
    loans = models.ForeignKey('Loans', related_name='transactions')

基本上,一个会员可以有一个到多个贷款,一个贷款可以有一个到多个交易(虽然它应该是0到多个,但我现在只是测试)。

我有一张表格要求会员的全名,贷款ID和金额。

基本上我试图根据全名找到会员,然后根据提供的ID获得贷款,然后为该贷款创建新的交易。

我在观点中所做的:

fullName = request.GET.get('full_name')
loanID = request.GET.get('loan_id')
amount = request.GET.get('amount')
#to get first name
firstName = fullName.partition(' ')[0]
#to get last name
lastName = fullName.rsplit(None, 1)[-1]
#to get the member
member = Member.objects.filter(first_name=firstName, last_name = lastName)
#get member's loan based on loanID
l = Loans(loan_id = loanID)
t = Transactions.objects.create(amount = amount, transactions = l)
t.save()

提交表单时出错:

  

'记录'是此函数的无效关键字参数

我使用正确的方法但不了解模型关系吗? 还是我完全走错了路?

任何帮助/指示都将不胜感激,

提前致谢

2 个答案:

答案 0 :(得分:2)

尝试t = Transactions.objects.create(amount = amount, loans = l)

transactions中没有Transactions字段。有amountloans以及loansLoans

中的l个实例

答案 1 :(得分:0)

它也可以如下工作:

l = Loans.objects.get(loan_id = loanID)
t = Transactions.objects.create(loans = l,amount = amount, ,transaction_id=uuid.uuid4())
t.save()

您还可以将transaction_id作为主键,进一步将其用作另一个表的外键。