English 中文(简体)
解决以下执行工作的缓慢办法
原标题:A pythonic way to solve the following implementation

我有3个模型。

class Company(models.Model):

    name = models.CharField(_("Name"), max_length = 100, blank = True, null = True)
    address = models.CharField(_("Address"), max_length = 300, blank = True, null = True)

class WebSite(models.Model):

    WEBSITE_TYPE_CHOICES = (
        ( Google+ ,  Google+ ),
        ( Facebook ,  Facebook ),
        ( Orkut ,  Orkut ),
    )
    user = models.ForeignKey(User)
    website = models.URLField(blank = True, null = True)
    website_type = models.CharField(max_length = 15, choices = WEBSITE_TYPE_CHOICES, default =  Google+ )
    company = models.ForeignKey(Company, null=True, blank=True)

class Review(models.Model):

    rating = models.FloatField(blank = True, null = True) 
    review = models.TextField(blank = True, null = True)
    company = models.ForeignKey(Company, null=True, blank=True)
    website = models.ForeignKey(Website, null=True, blank=True)

我想显示我的数据。

CompanyA:

  1. Google - 5 reviews, Avg 3.4
  2. Orkut - 9 reviews, Avg 4.1
  3. Facebook - 12 reviews, Avg 4.3
  4. Anyother - 2 reviews, Avg 2

CompanyB:

  1. Google - 2 reviews, Avg 3
  2. Facebook - 5 reviews, Avg 4

我已经这样做了。

    final_list = company_list = []
    websites = Website.objects.select_related().filter(user = user)

    for website in websites:
        company = website.company
        if company is not None and company not in company_list:
            company_list.append(brand)
            company_websites = websites.filter(company = company)
            info = []
            for company_website in company_websites:
                company_type = company_website.website_type
                reviews = Review.objects.filter(company = company, website = company_website)
                no_of_reviews = len(reviews)
                average = reviews.aggregate(Avg( rating ))
                info.append({"type": company_type, "no_of_reviews": no_of_reviews,
                             "average": average[ rating__avg ]})
            final_list.append({"company": company.name, "stats": info})

www.un.org/spanish/ecosoc 准则有两个问题。

  1. It is wasting a lot of computation
  2. It also somehow appends empty lists in the final_list (BUGGY)

FYI: I believe .annotate() can be used, but I fail to understand how can I use it based on a column, which in my case is (company__name)

最佳回答

这将使你获得数据。

Review.objects.values(company, website__website_type).annotate(review_count=Count( id ), average=Avg( rating )).order_by( company )

使用{% regroup %}在模板中产出。

问题回答

我没有检测过这一点,这或许与你收到的其他答复不一样,但如果它帮助......。

companies = Company.objects.all()
company_ratings = []

for company in companies:
    websites = company.website_set.filter(user=user)
    new_data = []

    for website in websites:
        reviews = Reviews.objects.filter(website=website, company=company)
        ratings = [x.rating for x in reviews]
        count = len(ratings)
        new_data.append({ website : website,  count : count, 
                          average : float(sum(ratings))/count})

    company_ratings.append({ company :company,  ratings :new_data})




相关问题
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 ]="...

热门标签