Django JSONField isnull lookup - python

As far as I know you can't use __isnull lookups on django native JSONField. On the Internet I found this inactive issue.
As possible workaround we can of course use these hacks:
model.objects.filter(field__contains={'key': None}), which isn't so flexible since you might need to query multiple keys or whatever.
model.objects.exclude(field__key=True).exclude(field__key=False), which is hacky and works only for boolean data.
I hope there is a better way ((c) Raymond Hettinger) of doing this. Any advises will be appreciated. For now, I will go with the first approach

According to this (see the last, closing comment) the following should work model.objects.filter(field__key=None) (But obviously you should use the Django version with the fix).
The django docs
warn that
Since any string could be a key in a JSON object, any lookup other
than those listed below will be interpreted as a key lookup. No errors
are raised. Be extra careful for typing mistakes, and always check
your queries work as you intend.
and here they are

Related

Google Cloud NDB integer vs urlsafe IDs?

The google-cloud-ndb Python library provides two ways of generating identifiers for Datastore entities:
integer_id(): Returns the ID as an integer.
urlsafe(): Returns a base64 string of the key.
If I am creating a URL mapping to a specific entity (eg: /users/<user_id>/) can I use either of these ID options?
I assume there is some benefit to using the base64 encoded version for URLs? The only issue is it results in some pretty ugly URLs, so I prefer to use the integer for aesthetics.
Is there a technical benefit (like improved performance) to using either option?
the urlsafe keys are useful if you specify your own custom ids when creating entities, since your custom id may include characters that cannot go in a url.
Also the urlsafe key has the kind and project id baked into it, which can be handy in case you get some wires crossed and pass the wrong id to the wrong spot.
I wouldn't say there is a performance benefit.
Another note about the urlsafe keys is that the format did change recently. The ndb library is backwards compatible, so in general it should've been fine, but that's something that they could possibly do again in the future, so just be aware of that.

Django prefetch_related and select_related

I am wondering about the behaviour of prefetch_related() and select_related().
If I do something like Model.objects.filter(...).prefetch_related(), I notice that there are much less database queries occurring. So my initial guess is that, if one does not specify the needed look-ups in prefetch_related(), it will automatically go through all of the model fields and do the needed job. However, I cannot find any reference to it on the web, which seems pretty strange to me. Is my guess correct or am I missing something?
From the FineManual(tm) (emphasis is mine):
There may be some situations where you wish to call select_related()
with a lot of related objects, or where you don’t know all of the
relations. In these cases it is possible to call select_related() with
no arguments. This will follow all non-null foreign keys it can find -
nullable foreign keys must be specified. This is not recommended in
most cases as it is likely to make the underlying query more complex,
and return more data, than is actually needed.

Passing string rather than function in django url pattern

In the Django docs it says about url patterns:
It is possible to pass a string containing the path to a view rather
than the actual Python function object. This alternative is supported
for the time being, though is not recommended and will be removed in a
future version of Django.
Does anyone have any insight as to why this the case? I find this alternative to be quite handy and can't find anything explaining why this is a bad (or, at least, less than ideal) idea.
I think the 1.8 Release Notes in the repo explains it quite well. Here's a summary of the main points:
In the modern era, we have updated the tutorial to instead recommend importing
your views module and referencing your view functions (or classes) directly.
This has a number of advantages, all deriving from the fact that we are using
normal Python in place of "Django String Magic": the errors when you mistype a
view name are less obscure, IDEs can help with autocompletion of view names,
etc.
Thus patterns() serves little purpose and is a burden when teaching new users
(answering the newbie's question "why do I need this empty string as the first
argument to patterns()?"). For these reasons, we are deprecating it.
Updating your code is as simple as ensuring that urlpatterns is a list of
:func:django.conf.urls.url instances.

How can I do this in SQLAlchemy?

I have an SQLAlchemy model, say Entity and this has a column, is_published. If I query this, say by id, I only want to return this if is_published is set to True. I think I can achieve using a filter. But in case there is a relationship and I am able to and require to access it like another_model_obj.entity and I only want this to give the corresponding entity object if the is_published for that instance is set to True. How should I do this? One solution would be wrap this around using an if block each time I use this. But I use this too many times and if I use it again, I will have to remember this detail. Is there any way I can automate this in SQLAlchemy, or is there any other better solution to this problem as a whole? Thank you
It reads as if you would need a join:
session().query(AnotherModel).join(Entity).filter(Entity.is_published)
This question was asked many times here and still doesn't have a good answer. Here are possible solutions suggested by the author of SQLAlchemy. A more elaborate query class to exclude unpublished objects is provided in iktomi library. It works with SQLAlchemy 0.8.* branch only for now but should be ported to 0.9.* soon. See test cases for limitations (tests that fail are marked with #unittest.skip()) and usage examples.

Is there a good language/syntax for field validation we can re-use?

I'm working on a web app (using Python & Bottle) and building a decorator for validating HTTP parameters sent in GET or POST. The early version takes callables, so this:
#params(user_id=int, user_name=unicode)
... ensures that user_id is an int, user_name is a string, and both fields exist.
But that's not enough. I want to be able to specify that user_name is optional, or that it must be non-empty and within 40 characters. Implementing that is easy enough, but I'm struggling with what syntax would be most elegant. It seems like that might be a problem someone's solved before, but I'm not finding an answer. Specifically I'm wondering if there's an elegant way to take parseable strings that provide the syntax. Something like:
#params(user_id='int:min1', user_name='unicode:required:max40')
I just don't want to invent a syntax if there's a good one floating around somewhere.
Anyone seen something like this? In any language..but I'm specifically valuing terseness and readability.
You could use lists.
#validate(user_id=[int, min(1)], user_name=[unicode,required,max(40)])
And each item could be a function (or class/object) that gets executed with the corresponding field as an argument. If it raises an error, it fails validation.

Categories