English 中文(简体)
Django最近租用的电影
原标题:Get least recently rented movies in Django

imagine:

CREATE movies (
    id int,
    name varchar(255),
    ...
    PRIMARY KEY (id)
);

CREATE movieRentals (
    id int,
    movie_id int,
    customer varchar(255),
    dateRented datetime,
    ...
    PRIMARY KEY (id)
    FOREIGN KEY (movie_id) REFERENCES movies(id)
);

我直截了当地认为:

(
    SELECT movie_id, count(movie_id) AS rent_count
    FROM movieRentals
    WHERE  dateRented > [TIME_ARG_HERE]
    GROUP BY movie_id
)
UNION
(
    SELECT id AS movie_id, 0 AS rent_count
    FROM movie
    WHERE movie_id NOT IN
    (
        SELECT movie_id
        FROM movieRentals
        WHERE dateRented > [TIME_ARG_HERE]
        GROUP BY movie_id
    )
)

(自指定日期起,按补贴计算所有电影租金)

显然,这些表格的Django版本是简单的模型:

class Movies(models.Model):
    name = models.CharField(max_length=255, unique=True)

class MovieRentals(models.Model):
    customer = models.CharField(max_length=255)
    dateRented = models.DateTimeField()
    movie = models.ForeignKey(Movies)

然而,将这一问题转化为一个相当的问题似乎很难:

timeArg = datetime.datetime.now() - datetime.timedelta(7,0)
queryset = models.MovieRentals.objects.all()
queryset = queryset.filter(dateRented__gte=timeArg)
queryset = queryset.annotate(rent_count=Count( movies ))

querysetTwo = models.Movies.objects.all()
querysetTwo = querysetTwo.filter(~Q(id__in=[val["movie_id"] for val in queryset.values("movie_id")]))
# Somehow need to set the 0 count. For now force it with Extra:
querysetTwo.extra(select={"rent_count": "SELECT 0 AS rent_count FROM app_movies LIMIT 1"})

# Now union these - for some reason this doesn t work:
# return querysetOne | querysetTwo
# so instead
set1List = [_getMinimalDict(model) for model in queryset]
# Where getMinimalDict just extracts the values I am interested in.
set2List = [_getMinimalDict(model) for model in querysetTwo]
return sorted(set1List + set2List, key=lambda x: x[ rent_count ])

然而,尽管这种方法似乎可行,但令人难以置信的是缓慢。 是否有更好的办法失踪?

最佳回答

简言之,这样的话会更容易:

SELECT movie.id, count(movieRentals.id) as rent_count
FROM movie
LEFT JOIN movieRentals ON (movieRentals.movie_id = movie.id AND dateRented > [TIME_ARG_HERE])
GROUP BY movie.id

左边会为自[TIME_ARG_HERE]以来未经许可的每部电影制作一个单行,但在这些行中,电影杂志。

然后,COUNT(movieRentals.id)将计算所有现有租金,如果只有NUL值,则将退还0。

问题回答

我必须失踪。 为什么要开展以下工作:

queryset = models.MovieRentals.filter(dateRented__gte=timeArg).values( movies ).annotate(Count( movies )).aggregate(Min( movies__count ))

此外,条款可以链条(如上法典所示),因此没有理由不断为中间点设定一个<代码>queryset变量。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签