我正在学习蟒蛇和django,我正在编写一个类似于IMDB的项目。我正在使用python 3.8.2 64位和django 3我想显示电影收到的最新评论,无论编写它的用户是谁。现在,它显示用户自己的最新评论,并且在注销用户后,评论将保留,而不会显示编写它的用户。我试图清除缓存和历史记录,没有帮助。这是模型:from django.db import modelsfrom django.contrib.auth.models import Userclass Movie(models.Model): movie_title = models.CharField(max_length=250) movie_poster = models.ImageField(default='default.png', blank=True) movie_short_description = models.TextField() director = models.CharField(max_length=250) actor1 = models.CharField(max_length=250) actor2 = models.CharField(max_length=250) actor3 = models.CharField(max_length=250) actor4 = models.CharField(max_length=250) year = models.IntegerField() def __str__(self): return self.movie_title + ' - ' + str(self.year)class Review(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, default = None, on_delete=models.DO_NOTHING) score = models.IntegerField() review_title = models.CharField(max_length=250, default="") movie_review = models.TextField() date = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'date' def __str__(self): return self.review_titleviews.pydef movie_detail(request, pk): try: movie = Movie.objects.get(pk=pk) review = Review.objects.all().latest() except Exception as e: print(e) return render (request, 'movies/movie_detail.html', {'movie': movie, 'review': review})代码: </table> </p> <p>User Reviews</p> <h3>Score: {{review.score}} {{review.review_title}}</h3> <h6>{{review.date}}, by {{ user.get_username }}</h6> <p>{{review.movie_review}}</p> <a href="{% url 'add_review' pk=movie.pk %}">Review this title</a> </div> </div>{% endblock %}
1 回答
三国纷争
TA贡献1804条经验 获得超7个赞
我会创建一个属性,为您提供所有评论,然后从此查询集中获取最新信息。代码如下:MovieReview
# models.py
class Movie(models.Model):
# your other code
@property
def reviews(self) -> QuerySet:
return self.review_set.all()
# views.py
def movie_detail(request, pk):
movie = get_object_or_404(Movie, pk=pk)
latest_review = movie.reviews.latest()
# return
Ps:我会重命名 ,并且只是 和 。很明显,这是电影的标题。我还强烈建议将 4 s 更改为具有 -relation 的单个模型(但我认为您稍后会在文档中阅读)。movie_titlemovie_postermovie_short_descriptiontitlepostershort_descriptiontitleMovieactorManyToMany
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报
0/150
提交
取消