So let's say I have the following models in Django:
所以我想说我在Django中有以下模型:
class Review(models.Model):
datetime = models.DateTimeField(("Date"), default=timezone.now)
class Rating(models.Model):
datetime = models.DateTimeField(("Date"), default=timezone.now)
And my view looks like this:
我的观点看起来像这样:
def get_page(request, id_slug):
context_dict = {}
reviews = Review.objects.filter(attribute=id_slug).order_by('-datetime')
ratings = Rating.objects.filter(attribute=id_slug).order_by('-datetime')
context_dict['reviews'] = reviews
context_dict['ratings'] = ratings
return render(request, 'page.html', context_dict)
What I want to do is make a query set that would include both Review and Rating objects, ordered by the datetime attribute, so something like:
我想要做的是创建一个查询集,其中包括由datetime属性排序的Review和Rating对象,如下所示:
activity = reviewsANDratings.order_by('-datetime')
context_dict['activity'] = activity
What would be the best way to achieve this?
实现这一目标的最佳方法是什么?
Thank you!
1 个解决方案
#1
0
If your models are basically the same thing, or parent/child of one another, consider using Django polymorphic, which will let you get all the Review
s and Rating
s in one PolymorphicQuerySet
.
如果您的模型基本上是相同的东西,或彼此的父/子,请考虑使用Django polymorphic,这将让您在一个PolymorphicQuerySet中获得所有评论和评级。
For more disparate models, (or for simpler implementation), just do two queries, like you are now, and merge the items in Python like so:
对于更多不同的模型(或者为了更简单的实现),只需执行两个查询,就像现在一样,并在Python中合并项目,如下所示:
reviews_and_ratings = sum([list(reviews), list(ratings)], [])
reviews_and_ratings.sort(key=lambda item: item.datetime, reverse=True)
context_dict['reviews_and_ratings'] = reviews_and_ratings
#1
0
If your models are basically the same thing, or parent/child of one another, consider using Django polymorphic, which will let you get all the Review
s and Rating
s in one PolymorphicQuerySet
.
如果您的模型基本上是相同的东西,或彼此的父/子,请考虑使用Django polymorphic,这将让您在一个PolymorphicQuerySet中获得所有评论和评级。
For more disparate models, (or for simpler implementation), just do two queries, like you are now, and merge the items in Python like so:
对于更多不同的模型(或者为了更简单的实现),只需执行两个查询,就像现在一样,并在Python中合并项目,如下所示:
reviews_and_ratings = sum([list(reviews), list(ratings)], [])
reviews_and_ratings.sort(key=lambda item: item.datetime, reverse=True)
context_dict['reviews_and_ratings'] = reviews_and_ratings