How do I use mathematical calculations on my forloop Article/Publication list?

70 views
Skip to first unread message

Pepsodent Cola

unread,
Nov 20, 2013, 4:29:24 PM11/20/13
to django...@googlegroups.com
1.)
How do I use mathematical calculations on my forloop Article/Publication list?

* I have attached a screenshot with the table field that I'm working on "Publicists coverage (%)".
* Admin user/pass = joe/joe
* I have also attached my project files so that you can see things for yourselves.


2.)
Is the solution I'm working with in "Index View page" the correct practice to do my mathematical calculations?

#_______________________________________________________________________________

def index(request):
    publications = Publication.objects.all()


    # sum_publications = Publication.objects.filter(article__pk=1).count()
    articles = Article.objects.all().annotate(num_publications=Count('publications'))
    #articles_int = int(articles)

    sum_publicists = Publication.objects.all().count()

    #publicists_coverage = articles/sum_publicists


#    context = {'publications':publications, 'sum_publicists':sum_publicists,
#               'publicists_coverage':publicists_coverage, 'articles':articles}
    context = {'publications':publications, 'sum_publicists':sum_publicists,
               'articles':articles}
    return render(request, 'magazine/index.html', context)
#_______________________________________________________________________________

<article>
    <h1>How many Publications was each Article in?</h1>

{% if articles %}
    <table border="1">
    <tr>
        <th>Article id</th>
        <th>Article</th>
        <th>Publication</th>
        <th>Publicists coverage (%)</th>
    </tr>
    {% for row in articles %}
    <tr>
        <td>{{ row.id }}</td>
        <td>{{ row.headline }}</td>
        <td>{{ row.num_publications }}</td>
        <td>({{ row.num_publications }} / {{ sum_publicists }}) = x %</td>
    </tr>
    {% endfor %}
    </table>
{% else %}
    <p>No Articles are available.</p>
{% endif %}

    <hr>
</article>

#_______________________________________________________________________________


3.)
When I try to convert articles object into int it doesn't work.  Am I going the wrong direction when thinking about solving things like this?


Exception Type: TypeError
Exception Value: int() argument must be a string or a number, not 'QuerySet'
Exception Location: /home/linux/Django/ManyToMany/magazine/views.py in index, line 17


>>> articles = Article.objects.all().annotate(num_publications=Count('publications'))
>>> type(articles)
<class 'django.db.models.query.QuerySet'>
>>> 
>>> articles_int = int(articles)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'QuerySet'
>>> 






02_Publicists_coverage.png
ManyToMany_public_02.tar.gz

James Turley

unread,
Nov 21, 2013, 5:58:47 AM11/21/13
to django...@googlegroups.com
On number 3, annotate returns the annotated queryset, not the particular result of the annotation. The annotation is added to each individual object in the set.

Turning that into an integer doesn't make sense, because num_publications is a property of each individual entry in the set, not the set itself.

articles[0].num_publications() would return the number of publications associated with the first article in the set, for example.

James


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/eaa87962-c182-4261-8668-69285dde8de3%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Pepsodent Cola

unread,
Nov 21, 2013, 12:53:00 PM11/21/13
to django...@googlegroups.com
1.)
I managed to make my View calculate my variables but I'm getting the same result "0.6" for each forloop.
What am I doing wrong with my variables calculation?

* I have attached an updated screenshot with the table field that I'm working on "Publicists coverage (%)".
* Admin user/pass = joe/joe
* I have also attached an update of my project files so that you can see things for yourselves.


#_______________________________________________________________________________

def index(request):
    publications = Publication.objects.all()


    # sum_publications = Publication.objects.filter(article__pk=1).count()
    articles = Article.objects.all().annotate(num_publications=Count('publications'))
    articles_int = articles.count()

    sum_publicists = Publication.objects.all().count()

    publicists_coverage = float(articles_int)/sum_publicists


    context = {'publications':publications, 'sum_publicists':sum_publicists,
               'publicists_coverage':publicists_coverage, 'articles':articles}
#    context = {'publications':publications, 'sum_publicists':sum_publicists,
#               'articles':articles}
    return render(request, 'magazine/index.html', context)
#_______________________________________________________________________________
   <h1>How many Publications was each Article in?</h1>

{% if articles %}
    <table border="1">
    <tr>
        <th>Article id</th>
        <th>Article</th>
        <th>Publication</th>
        <th>Publicists coverage (%)</th>
    </tr>
    {% for row in articles %}
    <tr>
        <td>{{ row.id }}</td>
        <td>{{ row.headline }}</td>
        <td>{{ row.num_publications }}</td>
        <td>({{ row.num_publications }} / {{ sum_publicists }}) = {{ publicists_coverage }}x %</td>
ManyToMany_public_03.tar.gz
03_Publicists_coverage.png

Pepsodent Cola

unread,
Nov 21, 2013, 1:04:38 PM11/21/13
to django...@googlegroups.com
@James

Now I understand what you mean. :)  I will work on this some more tonight.



On Wednesday, November 20, 2013 10:29:24 PM UTC+1, Pepsodent Cola wrote:

DJ-Tom

unread,
Nov 22, 2013, 3:40:32 AM11/22/13
to django...@googlegroups.com


Am Donnerstag, 21. November 2013 18:53:00 UTC+1 schrieb Pepsodent Cola:
1.)
I managed to make my View calculate my variables but I'm getting the same result "0.6" for each forloop.
What am I doing wrong with my variables calculation?

You are passing only a single value for publicists_coverage to the template - why do you expect to get a different value on each loop?

Currently there is no built-in way to do more than simple calculations via the "add" filter in templates, but you can easily create your own filters:

http://stackoverflow.com/questions/5848967/django-how-to-do-caculation-inside-the-template-html-page

Pepsodent Cola

unread,
Nov 23, 2013, 5:12:40 PM11/23/13
to django...@googlegroups.com
I worked some more on James' hint:  articles[0].num_publications() 

And I followed some tutorial exercises on making Template filters.  After seeing DJ-Tom's hint.

And this is as far as I got from trying things...
I'm trying to send two lists to my template so I can do some parallel iteration in my forloop.
But then I realized that type(articles) is a Queryset and not a list so I can't use zip() like in the examples I'm reading.

So how can I integrate my list
    publicists_coverage = [] # List 3
into this forloop template code?
    {% for row in articles %}


#_______________________________________________________________________________

def index(request):
    publications = Publication.objects.all()

    # sum_publications = Publication.objects.filter(article__pk=1).count()

    # List 1
    articles = Article.objects.all().annotate(num_publications=Count('publications'))
    #>>> type(articles)
    #<class 'django.db.models.query.QuerySet'>

    # 3
    publication_per_article = [] # List 2
    for i in range(articles.count()):
        x = articles[i].num_publications
        publication_per_article.append(x)

    # 5
    total_publicists = Publication.objects.all().count()

    # Calculate things!
    publicists_coverage = [] # List 3
    for row in publication_per_article:
        y = float(row)/total_publicists
        publicists_coverage.append(y)

    ziplist = zip(articles, publicists_coverage)
    context = {'publications':publications, 'articles':articles,
               'total_publicists':total_publicists, 'ziplist':ziplist}
#    context = {'publications':publications,
#               'total_publicists':total_publicists, 'ziplist':ziplist}
    return render(request, 'magazine/index.html', context)
#_______________________________________________________________________________

{% if articles and ziplist %}
    <table border="1">
    <tr>
        <th>Article id</th>
        <th>Article</th>
        <th>Publication</th>
        <th>Publicists coverage (%)</th>
    </tr>
    {% for row in articles %}
    <tr>
        <td>{{ row.id }}</td>
        <td>{{ row.headline }}</td>
        <td>{{ row.num_publications }}</td>
        <td>({{ row.num_publications }} / {{ total_publicists }}) = {{ publicists_coverage }}x %</td>
    </tr>
    {% endfor %}
    </table>
{% else %}
    <p>No Articles or Ziplist are available.</p>
{% endif %}








On Wednesday, November 20, 2013 10:29:24 PM UTC+1, Pepsodent Cola wrote:

Andre Terra

unread,
Nov 23, 2013, 8:05:30 PM11/23/13
to Django users
Take a look at the docs for aggregation and annotation and using F expressions in them. I just skimmed over your email, but there might be something useful to learn there.


Also, is there a reason why you're not using class based views?



Cheers,
AT


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

Pepsodent Cola

unread,
Nov 24, 2013, 5:55:06 AM11/24/13
to django...@googlegroups.com
Thanks airstrike I will check out your suggestions and study it.



Also, is there a reason why you're not using class based views?

Well as a newbie programmer I started out following the Django polls tutorial writing my views using CBVs.  But then when I had trouble doing things with my database and sending my database data through the Views and to the Template pages, since I'm not very familiar with MVC coding.
Explaining my MVC problems was very difficult and it took months before I could get any helpful hints, and when I did get help the CBV related help was too complicated for me to understand and study.

So after 6 months of trying to work with MVC, I signed up for a local Django Meetup.com meeting in real life.  There I grabbed a person who has worked with Django professionally most of their life and showed him my Django polls code project.

Explaining my problems was very difficult because CBVs confuse me so much.  I find it hard to see what is going on under the hood.
Then when I saw how this Django professional had a hard time untangling my View code.  Also he said using CBVs is the preferred way but writing function based Views is simpler to follow.

I then decided to get rid of all my CBVs and write function based Views only.  Suddenly the time it takes for me to explain my MVC problems and get help went down from months to only days. :)

On an academic level I realize using CBVs is the most efficient way but being a total Framework beginner I'm having trouble seeing the real practical advantage of using CBVs compared to simple function based Views.  The function based Views looks more cleaner and lighter to my eyes compared to CBV code and I find it easier to follow what is going on, less magic going on under the hood.







On Wednesday, November 20, 2013 10:29:24 PM UTC+1, Pepsodent Cola wrote:
Reply all
Reply to author
Forward
0 new messages