Storing Foreign Key, Not From The Form POST Method, But By Form Data I Already Have
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'
Solution 1:
Don't try to assign int
for payment.student
.
Assign student
instance.
payment.student = student.get(pk=1) # Desired value `1` for foreign key assumed
Moreover you should follow coding style rules (read about PEP8
):
- class names started with capital letters
- field names not started with capital letters
- variables and fields don't use camel case - class names do
Your code will work without this rules but as Python Developers we have some standards for readable code.
And in Django you don't have to define primary key field - it's created automatically and accessible with instance.pk
.
And I'm not sure if you really want your foreign key to point to student
column of student
table.
And you can just import student
model if it's defined in other module.
So with these corrections your class definition should be like:
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)
Now any Payment instance has implicit field pk
which stands for primary key.
And finnaly a line in your view with styling corrections:
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
Post a Comment for "Storing Foreign Key, Not From The Form POST Method, But By Form Data I Already Have"