How to get columns / fields with peewee query?

For model

class User(db.Model, BaseUser): name = CharField() phone = CharField() age = IntegerField() points = IntegerField() 

and the list of fields lst = ['phone', 'name', 'points']

Is there any way to return your query to fields in lst ?

I can't find an example in docs , but it looks like Django ORM has something like ...get().values(lst) .

I tried passing the list as an argument to User.select() , but getting

 TypeError: issubclass() arg 1 must be a class 

I think I could do something like [getattr(obj, field) for field in lst] with the resulting object, but it seems like there should be a better way?

Refresh . Link to values in Django docs here .

+6
source share
5 answers

You can use:

 User.select(User.phone, User.name, User.points) 

http://peewee.readthedocs.org/en/latest/peewee/api.html#SelectQuery

+8
source

You can use:

 lst = [User.phone, User.name, User.points] User.select(*lst) 

I use this method to dynamically select SELECT fields from a predefined list.

+3
source

Not sure what the problem is, but have you tried using object_list using fly peewee?

 def user_query(): lst_result = User.select().where(User.name == lst.name) return object_list('yourtemplate.html', lst_result, 'list_user') 

I apologize if you don’t really help.

Sincerely.

+1
source

This is old, but I recently found the answer.

Given an instance of u from the User table, then u._data returns a dictionary with the field name as keys.

For instance:

 db.connect() # db was established with connection parameters for your database u = User.get() # get one record print u._data # get dictionary with field names as keys db.close() # free up your connection 
0
source

The solution to this is to use tuples or dicts .

For example, for tuples from documents:

 stats = Stat.select(Stat.url, fn.Count(Stat.url)).group_by(Stat.url).tuples() # iterate over a list of 2-tuples containing the url and count for stat_url, stat_count in stats: print stat_url, stat_count 

For example, for dicts from documents:

 stats = Stat.select(Stat.url, fn.Count(Stat.url).alias('ct')).group_by(Stat.url).dicts() # iterate over a list of 2-tuples containing the url and count for stat in stats: print stat['url'], stat['ct'] 

Remember that the results are iterators, so if you want the entire tuple or dict in memory, you must initialize it using the default methods: tuple(stats) or dict(stats) .

More info here

0
source

Source: https://habr.com/ru/post/946544/


All Articles