如何找到同时显示评论对象和电视数据的方法



我做我想做的事

我想在comment对象中显示用户评论和由tv_id搜索的数据。

每个注释对象都有tv_id。

我想通过每个注释对象的TV_id获取数据,并将其与注释一起显示在HTML中。但是,我找不到同时显示评论对象和电视数据的方法。我该怎么做?

当前状态

class TV(models.Model):
id = models.CharField(primary_key=True, editable=False,
validators=[alphanumeric],max_length = 9999)
stars = models.FloatField(
blank=False,
null=False,
default=0, 
validators=[MinValueValidator(0.0),
MaxValueValidator(10.0)]
)
def get_comments(self):
return Comment_tv.objects.filter(tv_id=self.id)

def average_stars(self):
comments = self.get_comments()
n_comments = comments.count()
if n_comments:
self.stars = sum([comment.stars for comment in comments]) / n_comments
else:
self.stars = 0
return self.stars
class Comment_tv(models.Model):
class Meta:
unique_together = ('user', 'tv',)

comment     = models.TextField(max_length=1000)
stars       = models.FloatField(
blank=False,
null=False,
default=0, 
validators=[MinValueValidator(0.0),
MaxValueValidator(10.0)]
)
user        = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
tv          = models.ForeignKey(TV, on_delete=models.CASCADE)
created_at  = models.DateTimeField(auto_now_add=True)
updated_at  = models.DateTimeField(auto_now=True)
class Meta:
unique_together = ('user', 'tv')
indexes = [
models.Index(fields=['user', 'tv']),
]
data = requests.get(f"https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US")
class Comment_List_TV(ListView):
template_name = 'account/user_comment_list_tv.html'
def get_queryset(self):
Comment_list_query = Comment_tv.objects.none()
if self.request.user.is_authenticated:
Comment_list_query = Comment_tv.objects.filter(user=self.request.user)
return Comment_list_query

在泛型视图中添加context_object_name是一种很好的做法,这样您的模板中的查询集就会有一个更容易识别的名称。

class Comment_List_TV(ListView):
###
context_object_name = "comment_tv_list" # This is what the list will be called in the template
###
template_name = 'account/user_comment_list_tv.html'
def get_queryset(self):
Comment_list_query = Comment_tv.objects.none()
if self.request.user.is_authenticated:
Comment_list_query = Comment_tv.objects.filter(user=self.request.user)
return Comment_list_query

然后在您的模板中:

{% for comment_tv in comment_tv_list %}
{{ comment_tv.user }}
{{ comment_tv.comment }}
{{ comment_tv.stars }}
{{ comment_tv.tv.id }}
{% endfor %}

最新更新