Django的具有“ not in”过滤器的巨型列表性能? [英] Django performance with `not in` filter with giant list?

查看:120
本文介绍了Django的具有“ not in”过滤器的巨型列表性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在做一个学校项目,正在建立一个网站,让您对附近的餐馆(1-5星)进行评分。唯一的警告是,我将根据位置向用户显示餐厅(例如,最靠近的餐厅),并且一旦他们给餐厅评分,就永远不会再向他们显示。

I am currently making a school project where I am building a website that lets you rate nearby restaurants (1-5 stars). The only caveat is that I will show users the restaurants based on location (e.g. closest ones first) and that once they have rated a restaurant, it will never be shown to them again.

当前我有这样的想法

class User(models.Model):
    username = models.CharField(primary_key=True, max_length=20)
    location = models.SomeGeoPointField
    ...

class Restaurant(models.Model):
    title = models.CharField(primary_key=True, max_length=20)
    location = models.SomeGeoPointField
    ...

class Rating(models.Model):
    for    = models.ForeignKey(User, on_delete=models.CASCADE)
    from   = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    rating = models.IntegerField()

我在思考查询的外观时遇到了麻烦,如果我不在其中使用 过滤掉现有评级,关于可能的市盈率

I am having trouble thinking how the query would look like, and if I used a not in to filter out existing ratings, about the possible performance hit

推荐答案

您需要的查询是一个排除用户已评价的餐厅的查询。如果执行此操作,Django将创建一个有效的查询:

The query you need is one that excludes the restaurants which the user has already rated. Django will create an efficient query if you do this:

Restaurant.objects.exclude(rating__user=request.user)

如果您意识到这里的内容是多对多的关系,则可以使查询变得更加容易用户和餐厅,以及评级直通表。因此:

You can make the queries even easier if you recognise that what you have here is a many-to-many relationship between User and Restaurant, with a through table of Rating. So:

class User(models.Model):
    ...
    ratings = models.ManyToManyField('Restaurant', through='Rating', related_name='users_rating')

实际上实际上改变了这个查询-现在是:

This doesn't actually alter this query very much - now it is:

Restaurant.objects.exclude(users_rating=request.user)

但它肯定会使其他查询更容易。

but it will certainly make other queries easier.

这篇关于Django的具有“ not in”过滤器的巨型列表性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆