I'm here with a problem that does not quite know how to solve.
I have this query:
result = json.dumps([a.get_json() for a in Player.objects.filter(name=namepost)])
But now I want to return the result with paging, and do not really know how to do ... I've been seeing in the documentation to use the Paginator.
But for example when I do this
p = Paginator(result, 2)
print p.count
Gives 1609 ... and the result of the query is 3 records.
Someone can help me?
Related
i am new to django , would u experts pls kindly help me..
so i have two modules, and in CBV's get_context_data they both return total sum, now I want to add both the totals and display it on my HTML page, I honestly tried many things but I am always getting an error.
here is my views.py
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
today = datetime.datetime.now()
# Order.objects.filter(created_at__year=today.year, created_at__month=today.month)
context['expense1'] = Tracker.objects.filter(user=self.request.user)
context['Total1'] =(Body.objects.filter(user=self.request.user, pub_date__year=today.year, pub_date__month=today.month).aggregate(total=Sum(F('price') * F('quantity'))),
Sport.objects.filter(user=self.request.user, pub_date__year=today.year, pub_date__month=today.month).aggregate(total=Sum(F('price') * F('quantity'))))
return context
so what I want is , total of body + total of sports , which is being asgn to the context "total1" ,and then I want to show it in HTML
my HTML file
this is how I am displaying the total,
Total: {{Total1}}
Your oneliner code is a bit confusing but I think I get where you made the mistake - the aggregate returns a dict with the key in the argument as the return value. See below:
body_total = Body.objects.filter(
user=self.request.user, pub_date__year=today.year, pub_date__month=today.month
).aggregate(total=Sum(F('price') * F('quantity')))['total']
sport_total = Sport.objects.filter(
user=self.request.user, pub_date__year=today.year, pub_date__month=today.month
).aggregate(total=Sum(F('price') * F('quantity')))['total']
# Note: this is a tuple, not a sum of the two, so check what you need :)
context['Total1'] = (body_total, sport_total)
# For total sum of two totals, just add them of course.
# It seems like this is what you need from the post, and not the
# line above.
context['Total1'] = body_total + sport_total
PS. the code is not tested. I'm a bit unsure if the F expressions work fine (probably yes). Let me know if there are any issues.
In my fixturesquery below you can see I am filtering by the results of the teamsquery, and it works, but only for the first result of the teamsquery. So it only outputs the fixtures for the first userteam__userID=request.user
teamsquery = Team.objects.filter(userteams__userID=request.user)
fixturesquery = Fixtures.objects.filter(Q(hometeamID=teamsquery) |
Q(awayteamID=teamsquery))
How do i fix it so it outputs the fixtures for all the results of teamsquery?
If I understand correctly, your user can have multiplte teams, right?
If so, you can use:
teamsquery = Team.objects.filter(userteams__userID=request.user)
fixturesquery = Fixtures.objects.filter(Q(hometeamID__in=teamsquery)|Q(awayteamID__in=teamsquery))
I'm new to coding and have searched as best I can to find out how to solve this before asking.
I'm trying to pull information from poloniex.com REST api, which is in JSon format I believe. I can import the data, and work with it a little bit, but when I try to call and use the elements in the contained dictionaries, I get "'unicode' object not callable". How can I use this information? The end goal with this data is to pull the "BTC: "(volume)" for each coin pair and test if it is <100, and if not, append it to a new list.
The data is presented like this or you can see yourself at https://poloniex.com/public?command=return24hVolume:
{"BTC_LTC":{"BTC":"2.23248854","LTC":"87.10381314"},"BTC_NXT":{"BTC":"0.981616","NXT":"14145"}, ... "totalBTC":"81.89657704","totalLTC":"78.52083806"}
And my code I've been trying to get to work with currently looks like this(I've tried to iterate the information I want a million different ways, so I dunno what example to give for that part, but this is how I am importing the data):
returnvolume = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=return24hVolume'))
coinvolume = json.loads(returnvolume.read())
coinvolume = dict(coinvolume)
No matter how I try to use the data I've pulled, I get an error stating:
"unicode' object not callable."
I'd really appreciate a little help, I'm concerned I may be approaching this the wrong way as I haven't been able to get anything to work, or maybe I'm just missing something rudimentary, I'm not sure.
Thank you very much for your time!
Thanks to another user, downshift, I have discovered the answer!
d = {}
for k, v in coinvolume.items():
try:
if float(v['BTC']) > 100:
d[k] = v
except KeyError:
d[k] = v
except TypeError:
if v > 100:
d[k] = k
This creates a new list, d, and adds every coin with a 'BTC' volume > 100 to this new list.
Thanks again downshift, and I hope this helps others as well!
I want to concatenate two queryset obtained from two different models and i can do it using itertools like this:
ci = ContributorImage.objects.all()
pf = Portfolio.objects.all()
cpf = itertools.chain(ci,pf)
But the real fix is paginating results.If i pass a iterator(cpf, or our concatenated queryset) to Paginator function, p = Paginator(cpf, 10), it works as well but fails at retrieving first page page1 = p.page(1) with an error which says:
TypeError: object of type 'itertools.chain' has no len()
What can i do in case like this ?
The itertools.chain() will return a generator. The Paginator class needs an object implementing __len__ (generators, of course do not support it since the size of the collection is not known).
Your problem could be resolved in a number of ways (including using list to evaluate the generator as you mention) however I recommending taking a look at the QuerySetChain mentioned in this answer:
https://stackoverflow.com/a/432666/119071
I think it fits exactly to your problem. Also take a look at the comments of that answer - they are really enlightening :)
I know it's too late, but because I encountered this error, I would answer to this question.
you should return a list of objects:
ci = ContributorImage.objects.all()
pf = Portfolio.objects.all()
cpf = itertools.chain(ci,pf)
cpf_list = list(cpf)
Doing a search using django-sphinx gives me results._sphinx that says there were 68 results, but when I iterate over them, I can only get at the first 20 of them.
I'm SURE there's a way around this, and that this is by design, but it's officially stumping the heck out of me. Does anybody know how to get the complete queryset?
I figured this out finally.
Apparently, the querysets only return 20 hits until you access the queryset. Or something like that.
So, if you explicitly want the iterate over the whole thing, you have to do:
for result in results[0:results.count()]:
print result
Or something to that effect, which will query the entire thing explicitly. Ugh. This should be clearly documented...but it not.
After hacking through source, I set the _limit variable explicitly.. Does the job, and issues an actual limit:
qs = MyEntity.search.query(query_string)
qs._limit = limit
for result in qs:
print result
work for me:
in sphinx config file:
max_matches = 5000
in django code:
desc_obj = Dictionary.search.query( search_desc )
desc_obj._maxmatches = 5000
or in settings:
SPHINX_MAX_MATCHES = 5000