1

我发生在下面的一些查询中:

bphoto = B_Photo.objects.filter(q_user).order_by('-pub_date')
bactivity = B_Activity.objects.filter(q_user).order_by('-pub_date')
bpart = B_Part.objects.filter(q_user).order_by('-pub_date')

q_user 是一个 Q 对象,我想要的是对三个表中的所有结果进行排序,使用“pub_date”字段。

我怎样才能简化这种查询?

4

1 回答 1

2

B_PhotoB_Activity并且B_Part没有相同的表结构,对吧?我认为您不能使用三个不同的表进行查询。UNION 可以做到这一点,但它要求所有子查询返回具有相同结构的数据。

您似乎想要显示一个混合了照片、活动和部分的时间线。最合理的方法是在python中对结果进行排序。

bphoto = B_Photo.objects.filter(q_user).order_by('-pub_date')
bactivity = B_Activity.objects.filter(q_user).order_by('-pub_date')
bpart = B_Part.objects.filter(q_user).order_by('-pub_date')

timeline = sorted(bphoto + bactivity + bpart, key=lambda x:x.pub_date)

更新:

我明白你的意思了。如果您在这 3 个表中有太多数据,并且只想显示最近的,例如 20 条记录,您可以像这样在 3 个表上运行原始 UNION sql:

cursor = connection.cursor()
cursor.execute("SELECT id, type FROM (
    SELECT id, 'photo' AS type, pub_date FROM b_photo UNION 
    SELECT id, 'activity' AS type, pub_date FROM b_activity UNION 
    SELECT id, 'part' AS type, pub_date FROM b_part) AS my_query
    ORDER BY pub_date DESC LIMIT 20")
results = cursor.fetchall()
# results will be something like ((id, type), (id, type), ...)
# where type indicates what the id is (photo, activity or part)

然后使用 individualB_XXX.objects.get(id=id)获取每个对象ids

for result in results:
    if result[1] == 'photo':
        obj = B_Photo.objects.get(id=result[0])
    elif result[1] == 'activity':
        obj = B_Activity.objects.get(id=result[0])
    elif result[1] == 'part':
        obj = B_Part.objects.get(id=result[0])
    # do sth with obj...
于 2012-09-26T16:20:24.847 回答