I have the following code in a view:
lp_detail = LearningPathDetail()
pos_in_path = 1
lp_detail.lpheader_id = pk
lesson_ids = request.POST["lesson_ids"].split(",")
for lesson_id in lesson_ids:
lp_detail.id = ""
lp_detail.lesson_id = lesson_id
lp_detail.pos_in_path = pos_in_path
lp_detail.save()
pos_in_path = 1
pk is the ID from the header table that points back to the header record that identifies all of the detail records associated with it.
lesson_ids is a list of DB ids that need to be inserted into the lp_detail table.
What I think the code should do (according to the manual) based on the id being blank (I have also tried setting it to None)
is create the record, but instead I get an error:
Field 'id' expected a number but got ''.
Here is the model for the LearningPathDetail table:
class LearningPathDetail(models.Model):
lpheader = models.ForeignKey(LearningPathHeader, on_delete=models.CASCADE)
lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True)
pos_in_path = models.IntegerField(default=1)
I am not sure what I have incorrect here.
CodePudding user response:
Why would you want to set value of id
to empty string? Just delete this row:
lp_detail.id = ""
And let Django find good id by itself.
Also, I thin you want this:
lp_detail = LearningPathDetail()
Inside the loop. You might need new object with every iteration.
CodePudding user response:
Pk / Primary Key / Row Number cannot be blank.
It should just be something like: (and Django will take care of all the PK stuff
# get header
headerObj = LearningPathHeader.objects.get(pk=pk)
lesson_ids = request.POST["lesson_ids"].split(",")
pos_in_path = 1
for i in lesson_ids:
# Get lesson Object
lessonObj = Lesson.objects.get(pk=i)
# create detail Obj
LearningPathDetail.objects.create(
lpheader= headerObj,
lesson= lessonObj,
opos_in_path= pos_in_path.
)
pos_in_path = 1
if LearningPathHeader is unique to the LearningPathDetail. (Example only 1 path can have the header 'science') Then you'd just want to remove all the previous paths
lesson_ids = request.POST["lesson_ids"].split(",")
headerObj = LearningPathHeader.objects.get(pk=pk)
# delete all the old Path!
LearningPathDetail.filter(lpheader=headerObj).delete()
pos_in_path = 1
for i in lesson_ids:
lessonObj = Lesson.objects.get(pk=i)
LearningPathDetail.objects.create(
lpheader= headerObj,
lesson= lessonObj,
opos_in_path= pos_in_path.
)
pos_in_path = 1