Search Results

Search found 22 results on 1 pages for 'gqlquery'.

Page 1/1 | 1 

  • GAE/Django Templates (0.96) filters to get LENGTH of GqlQuery and filter it

    - by Halst
    I pass the query with comments to my template: COMM = CommentModel.gql("ORDER BY created") doRender(self,CP.template,{'CP':CP,'COMM':COMM, 'authorize':authorize()}) And I want to output the number of comments as a result, and I try to do things like that: <a href="...">{{ COMM|length }} comments</a> Thats does not work (yeah, since COMM is GqlQuery, not a list). What can I do with that? Is there a way to convert GqlQuery to list or is there another solution? (first question) Second question is, how to filter this list in template? Is there a construct like this: <a href="...">{{ COMM|where(reference=smth)|length }} comments</a> so that I can get not only the number of all comments, but only comments with certain db.ReferenceProperty() property, for example. Last question: is it weird to do such things using templates?

    Read the article

  • How can I Query only __key__ on a Google Appengine PolyModel child?

    - by Gabriel
    So the situation is: I want to optimize my code some for doing counting of records. So I have a parent Model class Base, a PolyModel class Entry, and a child class of Entry Article: How would I query Article.key so I can reduce the query load but only get the Article count. My first thought was to use: q = db.GqlQuery("SELECT __key__ from Article where base = :1", i_base) but it turns out GqlQuery doesn't like that because articles are actually stored in a table called Entry. Would it be possible to Query the class attribute? something like: q = db.GqlQuery("select __key__ from Entry where base = :1 and :2 in class", i_base, 'Article') neither of which work. Turns out the answer is even easier. But I am going to finish this question because I looked everywhere for this. q = db.GqlQuery("select __key__ from Entry where base = :1 and class = :2", i_base, 'Article')

    Read the article

  • Querying the Datastore in python

    - by Ray
    Greetings! I am trying to work with a single column in the datatstore, I can view and display the contents, like this - q = test.all() q.filter("adjclose =", "adjclose") q = db.GqlQuery("SELECT * FROM test") results = q.fetch(5) for p in results: p1 = p.adjclose print "The value is --> %f" % (p.adjclose) however i need to calculate the historical values with the adjclose column, and I am not able to get over the errors for c in range(len(p1)-1): TypeError: object of type 'float' has no len() here is my code! for c in range(len(p1)-1): p1.append(p1[c+1]-p1[c]/p1[c]) p2 = (p1[c+1]-p1[c]/p1[c]) print "the p1 value<-- %f" % (p2) print "dfd %f" %(p1) new to python, any help will be greatly appreciated! thanks in advance Ray HERE IS THE COMPLETE CODE class CalHandler(webapp.RequestHandler): def get(self): que = db.GqlQuery("SELECT * from test") user_list = que.fetch(limit=100) doRender( self, 'memberscreen2.htm', {'user_list': user_list} ) q = test.all() q.filter("adjclose =", "adjclose") q = db.GqlQuery("SELECT * FROM test") results = q.fetch(5) for p in results: p1 = p.adjclose print "The value is --> %f" % (p.adjclose) for c in range(len(p1)-1): p1.append(p1[c+1]-p1[c]/p1[c]) print "the p1 value<--> %f" % (p2) print "dfd %f" %(p1)

    Read the article

  • Filtering by entity key name in Google App Engine on Python

    - by Bemmu
    On Google App Engine to query the data store with Python, one can use GQL or Entity.all() and then filter it. So for example these are equivalent gql = "SELECT * FROM User WHERE age >= 18" db.GqlQuery(gql) and query = User.all() query.filter("age >=", 18) Now, it's also possible to query things by key name. I know that in GQL you do it like this gql = "SELECT * FROM User WHERE __key__ >= Key('User', 'abc')" db.GqlQuery(gql) But how would you now use filter to do the same? query = User.all() query.filter("__key__ >=", ?????)

    Read the article

  • On Google AppEngine what is the best way to merge two tables?

    - by gpjones
    If I have two tables, Company and Sales, and I want to display both sets of data in a single list, how would I do this on Google App Engine using GQL? The models are: class Company(db.Model): companyname = db.StringProperty() companyid = db.StringProperty() salesperson = db.StringProperty() class Sales(db.Model): companyid = db.StringProperty() weeklysales = db.StringProperty() monthlysales = db.StringProperty() The views are: def company(request): companys = db.GqlQuery("SELECT * FROM Company") sales = db.GqlQuery("SELECT * FROM Sales") template_values = { 'companys' : companys, 'sales' : sales } return respond(request, 'list', template_values) List html includes: {%for company in companys%} {% for sale in sales %} {% ifequal company.companyid sales.companyid %} {{sales.weeklysales}} {{sales.monthlysales}} {% endifequal %} {% endfor %} {{company.companyname}} {{company.companyid}} {{company.salesperson}} {%endfor%} Any help would be greatly appreciated.

    Read the article

  • GQL how to select by UserProperty

    - by fmsf
    Hey I have this code but it doesn't work because it is expecting a string. How can I make it work? class Atable(BaseModel): owner = db.UserProperty() (...) --------- // -------------- query = "SELECT * FROM Atable WHERE owner=", users.get_current_user() results = db.GqlQuery(query) How can I fix that search? Thanks :) I've started with the appengine database yesterday so be gentle :)

    Read the article

  • GQL select by UserProperty

    - by fmsf
    Hey I have this code but it doesn't work because it is expecting a string. How can I make it work? class Atable(BaseModel): owner = db.UserProperty() (...) --------- // -------------- query = "SELECT * FROM Atable WHERE owner=", users.get_current_user() results = db.GqlQuery(query) How can I fix that search? Thanks :) I've started with the appengine database yesterday so be gentle :)

    Read the article

  • How to check if datetime is older than 20 seconds.

    - by Jelle
    Hello! This is my first time here so I hope I post this question at the right place. :) I need to build flood control for my script but I'm not good at all this datetime to time conversions with UTC and stuff. I hope you can help me out. I'm using the Google App Engine with Python. I've got a datetimeproperty at the DataStore database which should be checked if it's older than 20 seconds, then proceed. Could anybody help me out? So in semi-psuedo: q = db.GqlQuery("SELECT * FROM Kudo WHERE fromuser = :1", user) lastplus = q.get() if lastplus.date is older than 20 seconds: print"Go!"

    Read the article

  • Can I specify the order of how changes happen in an single App Engine transaction ? Is it equal to t

    - by indiehacker
    If I passed a list of key ids as an argument in a transaction, would the change associated with the first key in the list happen first? And if not, how do I specify the order that I want the changes to happen in? As a concrete example, consider this code below from Google Docs Transactions--would changes to the first item in acc.key() happen first? class Accumulator(db.Model): counter = db.IntegerProperty() Docshttp://code.google.com/appengine/docs/python/datastore/transactions.html: def increment_counter(key, amount): obj = db.get(key) obj.counter += amount obj.put() q = db.GqlQuery("SELECT * FROM Accumulator") acc = q.get() db.run_in_transaction(increment_counter, acc.key(), 5)

    Read the article

  • Datastore query outputting for Django form instance

    - by Jelle
    Hello! I'm using google appengine and Django. I'm using de djangoforms module and wanted to specify the form instance with the information that comes from the query below. userquery = db.GqlQuery("SELECT * FROM User WHERE googleaccount = :1", users.get_current_user()) form = forms.AccountForm(data=request.POST or None,instance=?????) I've found a snippet in a sample app that does this trick, but I can't modify it to work with the query I need. gift = User.get(db.Key.from_path(User.kind(), int(gift_id))) if gift is None: return http.HttpResponseNotFound('No gift exists with that key (%r)' % gift_id) form = RegisterForm(data=request.POST or None, instance=gift) Could anyone help me?

    Read the article

  • Python appengine Query does not work when using a variable.

    - by Lloyd
    Hi, I am trying to use a fetcher method to retrieve items from my datastore. If I use the following def getItem(item_id): q = Item.all() q.filter("itemid = ", item_id) It fails because nothing is returned. If I hard code in an item like def getItem(item_id): q = Item.all() q.filter("itemid = ", 9000) it fetches just fine, and sings merrily along. I have tried every which way to get this to work. I have used result = db.GqlQuery("SELECT * FROM Item WHERE item_id = :1 LIMIT 1", title).fetch(1) to the same effect. If I hard code in a number, works fine. I have tried setting the select statement as a local string, assembling it that way, casting the int as a string, and nothing. When I output the SELECT statement to the screen, looks fine. I can cut ans paste the output into the string, and whammo, it works. Any help would be appreciated.

    Read the article

  • GAE datastore - count records between one minute ago and two minutes ago?

    - by Arthur Wulf White
    I am using GAE datastore with python and I want to count and display the number of records between two recent dates. for examples, how many records exist with a time signature between two minutes ago and three minutes ago in the datastore. Thank you. #!/usr/bin/env python import wsgiref.handlers from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from datetime import datetime class Voice(db.Model): when = db.DateTimeProperty(auto_now_add=True) class MyHandler(webapp.RequestHandler): def get(self): voices = db.GqlQuery( 'SELECT * FROM Voice ' 'ORDER BY when DESC') values = { 'voices': voices } self.response.out.write(template.render('main.html', values)) def post(self): voice = Voice() voice.put() self.redirect('/') self.response.out.write('posted!') def main(): app = webapp.WSGIApplication([ (r'.*', MyHandler)], debug=True) wsgiref.handlers.CGIHandler().run(app) if __name__ == "__main__": main()

    Read the article

  • How do I check for Existence of a Record in GAE

    - by VDev
    I am trying to create a simple view in Django & GAE, which will check if the user has a profile entity and prints a different message for each case. I have the program below, but somehow GAE always seem to return a object. My program is below import datetime from django.http import HttpResponse, HttpResponseRedirect from google.appengine.api import users from google.appengine.ext import db from models import Profile import logging #from accounts.views import profile # Create your views here. def login_view(request): user = users.get_current_user() profile = db.GqlQuery("SELECT * FROM Profile WHERE account = :1", users.get_current_user()) logging.info(profile) logging.info(user) if profile: return HttpResponse("Congratulations Your profile is already created.") else: return HttpResponse("Sorry Your profile is NOT created.") My model object is Profile defined as follows: class Profile(db.Model): first_name = db.StringProperty() last_name = db.StringProperty() gender = db.StringProperty(choices=set(["Male", "Female"])) account = db.UserProperty(required = True) friends = db.ListProperty(item_type=users.User) last_login = db.DateTimeProperty(required=True) Thanks for the help.

    Read the article

  • GAE Datastore Put()

    - by Ivan Slaughter
    def post(self): update = self.request.get('update') if users.get_current_user(): if update: personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update)) personal.name = self.request.get('name') personal.gender = self.request.get('gender') personal.mobile_num = self.request.get('mobile_num') personal.birthdate = int(self.request.get('birthdate')) personal.birthplace = self.request.get('birthplace') personal.address = self.request.get('address') personal.geo_pos = self.request.get('geo_pos') personal.info = self.request.get('info') photo = images.resize(self.request.get('img'), 0, 80) personal.photo = db.Blob(photo) personal.put() self.redirect('/admin/personal') else: personal= Personal() personal.name = self.request.get('name') personal.gender = self.request.get('gender') personal.mobile_num = self.request.get('mobile_num') personal.birthdate = int(self.request.get('birthdate')) personal.birthplace = self.request.get('birthplace') personal.address = self.request.get('address') personal.geo_pos = self.request.get('geo_pos') personal.info = self.request.get('info') photo = images.resize(self.request.get('img'), 0, 80) personal.photo = db.Blob(photo) personal.put() self.redirect('/admin/personal') else: self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.') Should this will update the existing record if the 'update' is querystring containing key datastore key. I try this but keep adding new record/entity. Please give me some sugesstion to correctly updating the record/entity. Correction? : def post(self): update = self.request.get('update') if users.get_current_user(): if update: personal = Personal.get(db.Key(update)) personal.name = self.request.get('name') personal.gender = self.request.get('gender') personal.mobile_num = self.request.get('mobile_num') personal.birthdate = int(self.request.get('birthdate')) personal.birthplace = self.request.get('birthplace') personal.address = self.request.get('address') personal.geo_pos = self.request.get('geo_pos') personal.info = self.request.get('info') photo = images.resize(self.request.get('img'), 0, 80) personal.photo = db.Blob(photo) personal.put() self.redirect('/admin/personal') else: personal= Personal() personal.name = self.request.get('name') personal.gender = self.request.get('gender') personal.mobile_num = self.request.get('mobile_num') personal.birthdate = int(self.request.get('birthdate')) personal.birthplace = self.request.get('birthplace') personal.address = self.request.get('address') personal.geo_pos = self.request.get('geo_pos') personal.info = self.request.get('info') photo = images.resize(self.request.get('img'), 0, 80) personal.photo = db.Blob(photo) personal.put() self.redirect('/admin/personal') else: self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')

    Read the article

  • Can I compare a template variable to an integer in App Engine templates?

    - by matt b
    Using Django templates in Google App Engine (on Python), is it possible to compare a template variable to an integer in an {% if %} block? views.py: class MyHandler(webapp.RequestHandler): def get(self): foo_list = db.GqlQuery(...) ... template_values['foos'] = foo_list template_values['foo_count'] = len(foo_list) handler.response.out.write(template.render(...)) My template: {% if foo_count == 1 %} There is one foo. {% endif %} This blows up with 'if' statement improperly formatted. What I was attempting to do in my template was build a simple if/elif/else tree to be grammatically correct to be able to state #foo_count == 0: There are no foos. #foo_count == 1: There is one foo. #else: There are {{ foos|length }} foos. Browsing the Django template documents (this link provided in the GAE documentation appears to be for versions of Django far newer than what is supported on GAE), it appears as if I can only actually use boolean operators (if in fact boolean operators are supported in this older version of Django) with strings or other template variables. Is it not possible to compare variables to integers or non-strings with Django templates? I'm sure there is an easy way to workaround this - built up the message string on the Python side rather than within the template - but this seems like such a simple operation you ought to be able to handle in a template. It sounds like I should be switching to a more advanced templating engine, but as I am new to Django (templates or any part of it), I'd just like some confirmation first.

    Read the article

  • "image contains error", trying to create and display images using google app engine

    - by bert
    Hello all the general idea is to create a galaxy-like map. I run into problems when I try to display a generated image. I used Python Image library to create the image and store it in the datastore. when i try to load the image i get no error on the log console and no image on the browser. when i copy/paste the image link (including datastore key) i get a black screen and the following message: The image “view-source:/localhost:8080/img?img_id=ag5kZXZ-c3BhY2VzaW0xMnINCxIHTWFpbk1hcBgeDA” cannot be displayed because it contains errors. the firefox error console: Error: Image corrupt or truncated: /localhost:8080/img?img_id=ag5kZXZ-c3BhY2VzaW0xMnINCxIHTWFpbk1hcBgeDA import cgi import datetime import urllib import webapp2 import jinja2 import os import math import sys from google.appengine.ext import db from google.appengine.api import users from PIL import Image #SNIP #class to define the map entity class MainMap(db.Model): defaultmap = db.BlobProperty(default=None) #SNIP class Generator(webapp2.RequestHandler): def post(self): #SNIP test = Image.new("RGBA",(100, 100)) dMap=MainMap() dMap.defaultmap = db.Blob(str(test)) dMap.put() #SNIP result = db.GqlQuery("SELECT * FROM MainMap LIMIT 1").fetch(1) if result: print"item found<br>" #debug info if result[0].defaultmap: print"defaultmap found<br>" #debug info string = "<div><img src='/img?img_id=" + str(result[0].key()) + "' width='100' height='100'></img>" print string else: print"nothing found<br>" else: self.redirect('/?=error') self.redirect('/') class Image_load(webapp2.RequestHandler): def get(self): self.response.out.write("started Image load") defaultmap = db.get(self.request.get("img_id")) if defaultmap.defaultmap: try: self.response.headers['Content-Type'] = "image/png" self.response.out.write(defaultmap.defaultmap) self.response.out.write("Image found") except: print "Unexpected error:", sys.exc_info()[0] else: self.response.out.write("No image") #SNIP app = webapp2.WSGIApplication([('/', MainPage), ('/generator', Generator), ('/img', Image_load)], debug=True) the browser shows the "item found" and "defaultmap found" strings and a broken imagelink the exception handling does not catch any errors Thanks for your help Regards Bert

    Read the article

  • Can I compare a template variable to an integer in Django/App Engine templates?

    - by matt b
    Using Django templates in Google App Engine (on Python), is it possible to compare a template variable to an integer in an {% if %} block? views.py: class MyHandler(webapp.RequestHandler): def get(self): foo_list = db.GqlQuery(...) ... template_values['foos'] = foo_list template_values['foo_count'] = len(foo_list) handler.response.out.write(template.render(...)) My template: {% if foo_count == 1 %} There is one foo. {% endif %} This blows up with 'if' statement improperly formatted. What I was attempting to do in my template was build a simple if/elif/else tree to be grammatically correct to be able to state #foo_count == 0: There are no foos. #foo_count == 1: There is one foo. #else: There are {{ foos|length }} foos. Browsing the Django template documents (this link provided in the GAE documentation appears to be for versions of Django far newer than what is supported on GAE), it appears as if I can only actually use boolean operators (if in fact boolean operators are supported in this older version of Django) with strings or other template variables. Is it not possible to compare variables to integers or non-strings with Django templates? I'm sure there is an easy way to workaround this - built up the message string on the Python side rather than within the template - but this seems like such a simple operation you ought to be able to handle in a template. It sounds like I should be switching to a more advanced templating engine, but as I am new to Django (templates or any part of it), I'd just like some confirmation first.

    Read the article

  • how to model a follower stream in appengine?

    - by molicule
    I am trying to design tables to buildout a follower relationship. Say I have a stream of 140char records that have user, hashtag and other text. Users follow other users, and can also follow hashtags. I am outlining the way I've designed this below, but there are two limitaions in my design. I was wondering if others had smarter ways to accomplish the same goal. The issues with this are The list of followers is copied in for each record If a new follower is added or one removed, 'all' the records have to be updated. The code class HashtagFollowers(db.Model): """ This table contains the followers for each hashtag """ hashtag = db.StringProperty() followers = db.StringListProperty() class UserFollowers(db.Model): """ This table contains the followers for each user """ username = db.StringProperty() followers = db.StringListProperty() class stream(db.Model): """ This table contains the data stream """ username = db.StringProperty() hashtag = db.StringProperty() text = db.TextProperty() def save(self): """ On each save all the followers for each hashtag and user are added into a another table with this record as the parent """ super(stream, self).save() hfs = HashtagFollowers.all().filter("hashtag =", self.hashtag).fetch(10) for hf in hfs: sh = streamHashtags(parent=self, followers=hf.followers) sh.save() ufs = UserFollowers.all().filter("username =", self.username).fetch(10) for uf in ufs: uh = streamUsers(parent=self, followers=uf.followers) uh.save() class streamHashtags(db.Model): """ The stream record is the parent of this record """ followers = db.StringListProperty() class streamUsers(db.Model): """ The stream record is the parent of this record """ followers = db.StringListProperty() Now, to get the stream of followed hastags indexes = db.GqlQuery("""SELECT __key__ from streamHashtags where followers = 'myusername'""") keys = [k,parent() for k in indexes[offset:numresults]] return db.get(keys) Is there a smarter way to do this?

    Read the article

  • GAE formpreview

    - by Niklas R
    I'm trying to enable form preview with Google App Engine. Getting the following error message I suspect being mistaken somewhere: ... handler = handler_class() TypeError: __call__() takes at least 2 arguments (1 given) Can you tell what's wrong with my attempt? Here is some of the code. from django.contrib.formtools.preview import FormPreview class AFormPreview(FormPreview): def done(self, request, cleaned_data): # Do something with the cleaned_data, then redirect # to a "success" page. self.response.out.write('Done!') class AForm(djangoforms.ModelForm): text = forms.CharField(widget=forms.Textarea(attrs={'rows':'11','cols':'70','class':'foo'}),label=_("content").capitalize()) def clean(self): cleaned_data = self.clean_data name = cleaned_data.get("name") if not name: raise forms.ValidationError("No name.") # Always return the full collection of cleaned data. return cleaned_data class Meta: model = A fields = ['category','currency','price','title','phonenumber','postaladress','name','text','email'] #change the order ... ('/aformpreview/([^/]*)', AFormPreview(AForm)), UPDATE: Here's a complete app where the preview is not working. Any ideas are most welcome: import cgi from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.db import djangoforms class Item(db.Model): name = db.StringProperty() quantity = db.IntegerProperty(default=1) target_price = db.FloatProperty() priority = db.StringProperty(default='Medium',choices=[ 'High', 'Medium', 'Low']) entry_time = db.DateTimeProperty(auto_now_add=True) added_by = db.UserProperty() class ItemForm(djangoforms.ModelForm): class Meta: model = Item exclude = ['added_by'] from django.contrib.formtools.preview import FormPreview class ItemFormPreview(FormPreview): def done(self, request, cleaned_data): # Do something with the cleaned_data, then redirect # to a "success" page. return HttpResponseRedirect('/') class MainPage(webapp.RequestHandler): def get(self): self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') # This generates our shopping list form and writes it in the response self.response.out.write(ItemForm()) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') def post(self): data = ItemForm(data=self.request.POST) if data.is_valid(): # Save the data, and redirect to the view page entity = data.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') else: # Reprint the form self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') self.response.out.write(data) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') class ItemPage(webapp.RequestHandler): def get(self): query = db.GqlQuery("SELECT * FROM Item ORDER BY name") for item in query: self.response.out.write('<a href="/edit?id=%d">Edit</a> - ' % item.key().id()) self.response.out.write("%s - Need to buy %d, cost $%0.2f each<br>" % (item.name, item.quantity, item.target_price)) class EditPage(webapp.RequestHandler): def get(self): id = int(self.request.get('id')) item = Item.get(db.Key.from_path('Item', id)) self.response.out.write('<html><body>' '<form method="POST" ' 'action="/edit">' '<table>') self.response.out.write(ItemForm(instance=item)) self.response.out.write('</table>' '<input type="hidden" name="_id" value="%s">' '<input type="submit">' '</form></body></html>' % id) def post(self): id = int(self.request.get('_id')) item = Item.get(db.Key.from_path('Item', id)) data = ItemForm(data=self.request.POST, instance=item) if data.is_valid(): # Save the data, and redirect to the view page entity = data.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') else: # Reprint the form self.response.out.write('<html><body>' '<form method="POST" ' 'action="/edit">' '<table>') self.response.out.write(data) self.response.out.write('</table>' '<input type="hidden" name="_id" value="%s">' '<input type="submit">' '</form></body></html>' % id) def main(): application = webapp.WSGIApplication( [('/', MainPage), ('/edit', EditPage), ('/items.html', ItemPage), ('/itemformpreview', ItemFormPreview(ItemForm)), ], debug=True) run_wsgi_app(application)

    Read the article

1