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
Related
I'm looking at the documentation (https://googleapis.dev/python/datastore/latest/queries.html) and it's not clear to me if it's possible to run a query that returns all members of an entity where a value exists in a ListProperty of those entities.
Example: if I have an Entity called Books with a field called tags that is a list of strings, is it possible for me to query for all Books with "fiction" in the Books.tags ListProperty?
This is the same as How to Query Google Cloud Datastore for array . You simply need an equality filter on tags. E.g. tags = "Fiction".
For python you can do it like this:
query = client.query(kind='KindName')
query.add_filter('tags', '=', 'fiction')
That returns you all entities which have 'fiction' in tag StringList property.
More information and insights you can get here.
UPD:
If you need to query only Books field you need to deploy composite indexes.
I have a table called user_info. I want to get names of all the users. So the table has a field called name. So in sql I do something like
SELECT distinct(name) from user_info
But I am not able to figure out how to do the same in django. Usually if I already have certain value known, then I can do something like below.
user_info.objects.filter(name='Alex')
And then get the information for that particular user.
But in this case for the given table, I want to get all the name values using django ORM just like I do in sql.
Here is my django model
class user_info(models.Model):
name = models.CharField(max_length=255)
priority = models.CharField(max_length=1)
org = models.CharField(max_length=20)
How can I do this in django?
You can use values_list.
user_info.objects.values_list('name', flat=True).distinct()
Note, in Python classes are usually defined in InitialCaps: your model should be UserInfo.
You can use values_list() as given in Daniel's answer, which will provide you your data in a list containing the values in the field. Or you can also use, values() like this:
user_info.object.values('name')
which will return you a queryset containing a dictionary. values_list() and values() are used to select the columns in a table.
Adding on to the accepted answer, if the field is a foreign key the id values(numerical) are returned in the queryset. Hence if you are expecting other kinds of values defined in the model of which the foreign key is part then you have to modify the query like this:
`Post.objects.values_list('author__username')`
Post is a model class having author as a foreign key field which in turn has its username field:
Here, "author" field was appended with double undersocre followed by the field "name", otherwise primary key of the model will be returned in queryset. I assume this was #Carlo's doubt in accepted answer.
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)
I have a model that looks something like this:
class Item(models.Model):
name = models.CharField()
type = models.CharField()
tags = models.models.ManyToManyField(Tags)
In order to render a given view, I have a view that presents a list of Items based on type. So in my view, there's a query like:
items = Item.objects.filter(type='type_a')
So that's easy and straight forward. Now I have an additional requirement for the view. In order to fulfill that requirement, I need to build a dictionary that relates Tags to Items. So the output i am looking for would be something like:
{
'tag1': [item1, item2, item5],
'tag2': [item1, item4],
'tag3': [item3, item5]
}
What would be the most efficient way to do this? Is there any way to do this without going to the database with a new query for each tag?
You can check prefetch_related it might help you:
This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different... prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related...
So in the end you will either do multiple queries or use prefetch_related and it will do some Python joins on the objects.
You might do something like this:
# This should require two database queries, one for the items
# and one for all the associated tags.
items = Item.objects.filter(type='type_a').prefetch_related('tags')
# Now massage the data into your desired data structure.
from collections import defaultdict
tag_dict = defaultdict(list)
for item in items:
# Thanks to prefetch_related this will not hit the database.
for tag in item.tags.all():
tag_dict[tag].append(item)
In django by default the form for a model foreign key is a ModelChoiceField (where you can select out of a list of all possible models). And it's possible to change these with the query set attribute, like
// in forms.py
self.fields['possible_cars'].queryset = somequeryset
But I'm in a situation where I have a list of stuff, not a queryset, and since there is no way to convert a list into a queryset, i'm not sure how to make the options for my ModelChoiceField similar to the list of models I want. (Since they take a queryset by default, i'm assuming they get a list from that query anyways, so this kinda thing should be possible).
I tried self.fields['possible_cars']._choices = mylist , but it won't work.
Any ideas guys?
Assuming your field take a Car queryset, you can construct one like the following:
mylist = ['BMW', 'Lamborghini', 'Porsche']
cars = Car.objects.filter(name__in=mylist)
self.fields['possible_cars'].queryset = cars