简体   繁体   中英

Pass model objects to choices field in django

I have a model called Student that has a manytomany relationship with a model called Courses . I have another model called Attend in which I want to get all the courses the student is taking and pass it in as a select menu containing the courses the student is taking. I tried to get the id using the foreign key "student" and then get courses belonging to that student and put it in a list and pass it to choices but it didn't work obviously. I would like to know how I can get the courses belonging to the student to appear in the select menu.

Here is my model.

class Attend(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, default="")
    time_signed_in = models.DateTimeField(auto_now_add=True)
    isSignedIn = models.BooleanField(default=False)
    # Below does not work, I get an error 'ForeignKey' object has no attribute 'id'

    #courses = User.objects.get(id=student.id).courses
    course = models.ForeignKey(Course, on_delete=models.CASCADE) 

To render the courses the student is taking you should try using django forms .

If I understand correctly, you want a form that uses ModelMultipleChoiceField :

Allows the selection of one or more model objects, suitable for representing a many-to-many relation.

class AttendForm(forms.Form):
    courses = forms.ModelMultipleChoiceField(queryset=Courses.objects.filter(student__id=id))

That exapmple would only work to show the data to the user and then retrieving its choice. There is a slightly different approach to this case and that is using a ModelForm .

Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form.

ModelForm is a "database driven" form in which you can perform many task involving calls to the database easily.

Note: The queryset I used in the example is just an example, you dont have to use it that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM