I was wondering if there was any handy helpers in Django which would return the results of a query into a more 'usuable' format so I don't have to iterate through them in my view.
I have a query like this:
self.filter(key__in=keys).values('key','value')
What I want to end up is an object which looks like
{'some_key':'some value', 'some_other_key':'some_other_value'}
So in my model I could do something like this:
settings = Setting.objects.get_keys(['some_setting','some_other_setting'])
print settings.some_setting # returns 'some value'
Where 'get_keys' is a manager function which runs the above filter query. Any idea how I might do this? I wouldn't be opposed to iterating through the results in the Settings Manager because I could store them for later... I couldn't quite figure our how to create a 'global' model variable though.
Any help would be greatly appreciated!
If you use values_list rather than values, it will return a set of two-tuples, which you can then pass to dict() to create a dictionary:
return dict(self.filter(key__in=keys).values_list('key','value'))
I think what you're looking for is: http://docs.djangoproject.com/en/stable/ref/models/querysets/#in-bulk
This function takes a list of primary keys and return a dictionary of the models mapped to the keys. It sounds like this is exactly what you want?
Related
I would like to turn this:
http://127.0.0.1:8000/fields_data/?field_name__exact=053&field_name__exact=064
into this:
fields = Fields.objects.filter(Q(field_name__exact='053')| Q(field_name__exact=field'064))
There could be additional numbers of field_name__exacts, it's not known until runtime.
In views.py, I can turn the URL into a QueryDict easily because request.GET is already a QueryDict object. According to the docs, QueryDict was designed in part so that the same key name could be used with multiple values, a common pattern in urls.
I then try to turn the QueryDict into something compatible with **kwargs by using:
fields = serialize('geojson', Fields.objects.filter(**request.GET.dict())), but request.GET.dict() looks like this:
{'field_name__exact': ['053', '064']}. As a result, I only ever get back the second object.
I'm starting to suspect I may need to write something more sophisticated involving comprehensions, but I feel like I'm really close. Can someone help me with the correct syntax to turn the QueryDict (multi-valued keys) into an OR'd set of Q()'s?
You can use list comprehension here:
from django.db.models import Q
Fields.objects.filter(
Q(*[(k,v) for k,vs in request.GET.lists() for v in vs], _connector=Q.OR)
)
This will then make a query that makes a logical OR between the items in the QueryDict.
I have a list of UUIDs that represent users in a DB table. I want to fetch all the users that match this criteria so I use the __in filter:
users = User.objects.filter(user__in=uuids)
I would like to raise an exception if not all of the UUIDs appear in the table. In other words, I expect to get a result back for each uuid such that len(users) == len(uuids). Is there an easy Django way to do it? If not, is there an easy way for me to create this behavior?
You could use exclude if you like it gives you the objects that does not match the query
#this returns true if one or more and dont need to use len()
#if it looks better for you you can try it out
#if everything is fine will return None
if User.objects.filter().exclude(user__in=uiids).first():
raise your_error
Don't think too complicated. You want to know if a list of something is fully contained in another list of something, that's just plain python:
user_ids = User.objects.values_list('user_id',flat=True)
if not set(uuids).issubset(user_ids): # or use .difference() to get the uuids missing from user_ids
raise stuff
I'm parsing a dictionary in Django from the request.
I know I can extract the value using the key name like so: myDict=request_data['myDict']
now i would like to do this obj1= myDict[0] instead of obj1= myDict['obj1']
but it doesn't seems to work, ant suggestions?
Different from a list a dictionary has 'keys'. I'm guessing you are referring to the iterating over the different keys that your dictionary has.
what you want to do is something like this:
keys = myDict.keys()
obj1 = myDict[keys[0]]
I have a query like this:
file_s = Share.objects.filter(shared_user_id=log_id)
Now, I want to get the files_id attribute from file_s in Django view. How can I do that?
Use values() to get particular attribute which will return you list of dicts, like
file_s = Share.objects.filter(shared_user_id=log_id).values('files_id')
EDIT: If you want only one attribute then you can use flat=True to suggest to return just list of values. However, make sure in what order the list will be.
file_s = Share.objects.filter(shared_user_id=log_id).values_list('files_id', flat=True).order_by('id')
Your Share.objects.filter() call returns a Djagno QuerySet object which is not a single record, but an iterable of filtered objects from the database with each item being a Share instance. It's possible that your filter call will return more than one item.
You can iterate over the QuerySet using a loop such as:
for share in files_s:
print share.files_id
If you know that your query is only expected to return a single item, you could do:
share = Share.objects.get(shared_user_id=log_id)
which will return a single Share instance from which you can access the files_id attribute. An exception will be raised if the query would return anything other than 1 result.
If you want to get only the value from a single value QuerySet you can do:
file_s = Share.objects.filter(shared_user_id=log_id).values_list('files_id', flat=True).first()
I have a URL with parameters such as:
field1__lt=7&field2__contains=bar
I understand how to get these values from the cleaned_data dict, but how can I put them into filter() statements? filter doesn't seem to like the key being a string.
This is for trusted users only, so there are no security concerns.
Use dict unpacking. If you have a dict like {'field1__lt':7, 'field2__contains':'bar'} in a variable lookups, then you can write filter(**lookups).
I think you need to pass few arguments in .filter method? Then you will need to use Q objects. So, something like this will work correctly.
MyModel.objects.filter(Q(field1__lt=7)&Q(field2__contains=bar))