在Django中以不同模型的形式显示多对多?

时间:2022-10-04 16:25:29

Say I have three models, a Professor model, a Course model, and a Review model. The user is allowed to make a Review, which reviews a Professor that teaches a certain Course.

假设我有三个模型,一个教授模型,一个课程模型,一个复习模型。用户可以对教授某门课程的教授进行评审。

I'm thinking of how to model the many to many relationship of Professor and Course, and how to reference that relationship in Review. My idea so far is to use models.ManyToMany to link Professor and Course.

我正在思考如何模拟教授和课程之间的许多关系,以及如何在复习中引用这种关系。到目前为止,我的想法是使用模型。许多人把教授和课程联系在一起。

Models.py (Prof)

模型。py(教授)

class Prof(models.Model):
first_name = models.CharField(max_length = 20, unique = False)
last_name = models.CharField(max_length = 20, unique = False)

    def __str__ (self):
        return self.first_name + " " + self.last_name

class Course(models.Model):
    name = models.CharField(max_length = 20, unique = True)
    prof = models.ManyToManyField(Prof)

    def __str__ (self):
        return self.name

Models.py (Review)

模型。py(审查)

class Review(models.Model):
    message = models.TextField(max_length = 4000)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(null = True)
    rating = models.IntegerField(
        default = 5, 
        validators = [MaxValueValidator(5), MinValueValidator(0)]
    )
    prof = models.ForeignKey(Prof, related_name = 'reviews')
    course = models.ForeignKey(Course, related_name = 'reviews')
    user = models.ForeignKey(User, related_name = 'reviews')

    def __str__ (self):
        return self.message   

forms.py

forms.py

class ReviewForm(ModelForm):
    rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5}))

    class Meta:
        model = Review
        fields = ['message', 'rating', 'prof', 'course', 'user']

This is my code so far for displaying the form

到目前为止,这是显示表单的代码

<h1>New Review</h1>
<form method="POST">
    {% csrf_token %}
    <p>{{ review_form.message }}</p>
    <p>{{ review_form.rating }}</p>
    <p>{{ review_form.prof }}</p>
    <!-- The prof chosen's courses should be shown here -->
    <button type="submit">Save</button>
</form>

Right now, forms.py shows all the objects under Course, and i'm not sure how to instead show the courses of a professor. Is it possible to filter the form after a prof is chosen from the drop down, to display the courses he/she teacher?

现在,形式。py显示了课程中所有的对象,我不知道如何替代教授的课程。是否有可能在从下拉菜单中选择教授后过滤表格,以显示他/她的老师的课程?

1 个解决方案

#1


1  

It sounds like you're going about this the right way. You haven't mentioned your urls.py structure yet, or views.py but the most straightforward way to do this is to display the courses by professor, taking the professor's id (or slug-field) in as a parameter - either in the URL (v straightforward) or as the output from a form on a previous page (and reload the template with a professor parameter) or in Ajax, depending on your appetite for shiny-new-things.

听起来你做得对。您还没有提到您的url。py结构,或者视图。py但最简单的方法是显示课程教授,教授的id作为参数(或slug-field)——在URL(v直截了当)或在前一页的输出形式(教授和重新加载模板参数)或Ajax对shiny-new-things取决于您的需求。

In your view, when you call the form, you can then do, along the lines from this answer -

在您的视图中,当您调用这个表单时,您可以按照这个答案的行来做

form.courses.queryset = Course.objects.filter(professor__in=[professor.id,])

form.courses。queryset = Course.objects.filter(professor__in =[professor.id,])

Note that I've put filtered on a list here, which only has one item - it does give you scope to expand, or to use a queryset for more complicated functions later.

注意,我在这里将filter放在一个列表中,这个列表只有一个条目——它确实为您提供了扩展的范围,或者稍后为更复杂的函数使用一个queryset。

Tweak as appropriate if you're using class-based views. :)

如果您正在使用基于类的视图,请适当地进行调整。:)

#1


1  

It sounds like you're going about this the right way. You haven't mentioned your urls.py structure yet, or views.py but the most straightforward way to do this is to display the courses by professor, taking the professor's id (or slug-field) in as a parameter - either in the URL (v straightforward) or as the output from a form on a previous page (and reload the template with a professor parameter) or in Ajax, depending on your appetite for shiny-new-things.

听起来你做得对。您还没有提到您的url。py结构,或者视图。py但最简单的方法是显示课程教授,教授的id作为参数(或slug-field)——在URL(v直截了当)或在前一页的输出形式(教授和重新加载模板参数)或Ajax对shiny-new-things取决于您的需求。

In your view, when you call the form, you can then do, along the lines from this answer -

在您的视图中,当您调用这个表单时,您可以按照这个答案的行来做

form.courses.queryset = Course.objects.filter(professor__in=[professor.id,])

form.courses。queryset = Course.objects.filter(professor__in =[professor.id,])

Note that I've put filtered on a list here, which only has one item - it does give you scope to expand, or to use a queryset for more complicated functions later.

注意,我在这里将filter放在一个列表中,这个列表只有一个条目——它确实为您提供了扩展的范围,或者稍后为更复杂的函数使用一个queryset。

Tweak as appropriate if you're using class-based views. :)

如果您正在使用基于类的视图,请适当地进行调整。:)