1

I am storing 'payment' model instance via form POST method but I have the data of the foreign key field already, because I am coming from a page which list the objects of 'student' model. I am storing the field of foreign key by input type="hidden" html element.

but when I submit, it shows error

> Cannot assign "u'1'": "payment.student" must be a "student" instance.
> Request Method:   POST
> Django Version:   1.5.2
> Exception Type:   ValueError
> Exception Value:  
> Cannot assign "u'1'": "payment.student" must be a "student" instance.
> Exception Location:   /usr/local/lib/python2.7/dist-> > > > >packages/django/db/models/fields/related.py in __set__, line 405
>Python Executable: /usr/bin/python
>Python Version:    2.7.3

This is my model:

class payment(models.Model):
    Id = models.AutoField(primary_key=True)
    student = models.ForeignKey('student',db_column='student')
    dateTime = models.DateField(auto_now_add=True)
    amountDue = models.DecimalField(max_digits=5, decimal_places=2)

I added later added db_column='student' but it might not have really taken effect in mysql database.

4

1 回答 1

0

不要尝试分配intfor payment.student。分配student实例。

payment.student = student.get(pk=1) # Desired value `1` for foreign key assumed

此外,您应该遵循编码风格规则(阅读有关PEP8):

  • 类名以大写字母开头
  • 不以大写字母开头的字段名称
  • 变量和字段不使用驼峰式大小写 - 类名使用

你的代码可以在没有这些规则的情况下工作,但作为 Python 开发人员,我们有一些可读代码的标准。

在 Django 中,您不必定义主键字段 - 它是自动创建的,并且可以使用instance.pk.
而且我不确定你是否真的希望你的外键指向表的studentstudent。如果模型在其他模块中定义,
您可以只导入模型。student

因此,通过这些更正,您的类定义应如下所示:

from other_app.models import Student

class Payment(models.Model):
    student = models.ForeignKey(Student)
    date_time = models.DateField(auto_now_add=True)
    amount_due = models.DecimalField(max_digits=5, decimal_places=2)

现在任何 Payment 实例都有隐含字段pk,它代表主键。最后在您的视图中有一条带有样式更正的线:

payment.student = Student.get(pk=1) # Desired value `1` for foreign key assumed
# payment is instance so all lowercase here
# Student on the right side is a class so started with capital
于 2013-09-13T16:01:40.727 回答