How to use a list inside values_list() in django? - python

I am new to python and django.I am having a list obtained dynamically containing database table fieldnames. How do I use this list within values_list() in django queryset while fetching results from database?
fieldList=['field1','field2'] #list containing table fields
obj=sampletable.objects.filter(somecondition).values_list(fieldlist) #--->want like this
I came to know that we can't use lists simply as it is inside values_list().So I converted it into a string like this and then tried it but in vain.
fieldListstr=','.join(repr(e) for e in fieldList)
This is the error which I got
Cannot resolve keyword "'field1','field2'" into field. Choices are: field1, field2
Please help me with your solutions. And thanks in advance

Simply unpack them,
.values_list(*fieldlist)

You can use argument list unpacking to pass the values of a list as arguments to a function like so:
values_list(*fieldlist)

Related

dynamic query sorting with Peewee

I'm having trouble assembling dynamic sorting with my Peewee python app.
Catalog is a Model object from playhouse.signals
Database is MariaDB
I can sort by 2 fields like this:
resultset = Catalog.select().where(...).order_by(Catalog.app_team,Catalog.domain)
I can use a dynamic sort field like this:
sortlist = []
opt = 'domain'
sortlist.append(getattr(Catalog,opt))
resultset = Catalog.select().where(...).order_by(sortlist)
But I can't see how to do more than one dynamic field. It fails if I pass it a list of 2 objects.
I tried passing a string like 'Catalog.app_team,Catalog.domain' but a string is ignored.
Any help is much appreciated.

How to use django ORM to query database

I have a model called 'dboinv_product' and this model has a field called 'product_name'
I need to use Django ORM in my views.py file to pull ALL the product names. The goal is to put it into a list this way I can serialize it using JSON.
Does anyone know which Django command(s) can be used to produce this list?
Essentially, I need the equivalent of "SELECT ALL product_name FROM dbo.inv_product"
values_list is what you are looking for.
value= dboinv_product.objects.values_list('product_name', flat=True)
list = list(value) # to convert to a list
# flat=True to get list rather than tuple inside of the ValuesListQuerySet.
The document about values_listis here. 1

Django: SELECT JsonField AS new_name?

I have a table, in which some attributes are columns, and some are implemented as a postgres JsonField.
For the columns, I can write eg
Product.objects.values(brand=F('brand_name'))
for implement a SELECT brand_name AS brand query.
I need to do something similar for a JsonField, eg
Product.objects.values(color=F('jsonproperties__color'))
However, the F expressions do not work correctly with JsonFields, and there doesn't seem to be a fix coming anytime soon.
How could I work around this?
Perhaps a simple list comprehension will do what you want:
[{"color": p["jsonproperties"]["color"]} for p in Product.objects.values("color")]

Dynamically Create Query String for Django > MySQL from JSON

I am new to Django and am having some issues writing to a MySQL dB. What I am trying to do is loop through nested JSON data, and dynamically create a string to be used with a save() method.
I've looped through my nested JSON data and successfully created a string that contains the data I want to save in a single row to the MySQL table "mysqltable":
q = "station_id='thisid',stall_id='thisstaull',source='source',target='test'"
I then try to save this to the table in MySQL:
b = mysqltable(q)
b.save()
But I am getting the error:
TypeError: int() argument must be a string or a number, not 'mysqltable'
What I think is happening is that it doesn't like the fact I have created a string to use in b = mysqltable(q). When I just write out the statement like the below it works fine:
q = mysqltable(station_id='thisid',stall_id='thisstaull',source='source',target='test')
q.save()
But I am not sure how to take that string and make it available to use with b.save(). Any help would be greatly appreciated!
Instead string, create a dictionary, and then pass it directly to mysqltable:
mysqltable(**dictWithData)
Of course you can re-parse string onto dictionary, but this is useless work...

Python Lists and MongoDB insert

Need help in understanding what is happening here and a suggestion to avoid this!
Here is my snippet:
result = [list of dictionary objects(dictionary objects have 2 keys and 2 String values)]
copyResults = list(results);
## Here I try to insert each Dict into MongoDB (Using PyMongo)
for item in copyResults:
dbcollection.save(item) # This is all saving fine in MongoDB.
But when I loop thru that original result list again it shows dictionary objects with a new field added
automatically which is ObjectId from MongoDB!
Later in code I need to transform that original result list to json but this ObjectId is causing issues.No clue why this is getting added to original list.
I have already tried copy or creating new list etc. It still adds up ObjectId in the original list after saving.
Please suggest!
every document saved in mongodb requires '_id' field - which has to be unique among documents in the collection. if you don't provide one, mongodb will automatically create one with ObjectId (bson.objectid.ObjectId for pymongo)
If you need to export documents to json, you have to pop '_id' field before jsonifying it.
Or you could use:
rows['_id'] = str(rows['_id'])
Remember to set it back if you then need to update

Categories

Resources