This utility is useful when you want to safely retrieve a single object from the database without having to wrap get() in a try/except block every time.
It also supports query optimization via select_related and prefetch_related, making it ideal for performance-conscious applications.
Here's how to find the 10 closest locations to a point for a model that has latitude and longitude columns, if you're not using GeoDjango.
This runs a brute force distance calculation against every row, so it should only be used on smaller tables - probably less than 100,000 rows.
For larger tables you should use GeoDjango instead.
See also [my TIL](https://til.simonwillison.net/postgresql/closest-locations-to-a-point) about this.
Django's CharField requires a max_length, and TextField displays a multi-
line widget, but in Postgres there's no reason to add an arbitrary max
thanks to the `varlena` storage format. So this is a TextField that
displays as a single line instead of a multiline TextArea.
I want to create Mixins for QuerySet objects that will by default filter out certain records (e.g. filter out "deleted" records, or filter out "unapproved" records, etc). I'd like those to be separate independent mixins. So in each of those, I override all() to filter out deleted or unapproved, etc.
But, I also want to offer a method in the queryset to remove those filters or remove some part of those filters.
That's where this code comes in. After some examination of how QuerySets work, this seemed like the simplest method for "undoing" some filter in a queryset
This is a quite simple snippet to integrate postgresql trgm search in django 1.6.10
This snippet is easy to adapt to other special operators by changing the trgm_search function. This example uses the operator `%%` but you could use `ts_vector(fieldname) @@ to_tsquery(%s)`
The recipe uses deferred constraint validation to create circular references across database tables. The example requires Postgres (MySQL doesn't support deferred constraints).
To achieve this, the following is required:
* Insertions must be performed in a transaction. Foreign key constraints will be validated at the end of the transactions, allowing for insertion of rows with FKs pointing to rows that don't exist yet.
* Primary keys need to be generated before insertion. That's what `prefetch_id` does by pulling the next value from the `*_id_seq` sequence.
Get derived model without storing their names or content types in databases. You write only one line, it expands into only one SQL-query (with many LEFT OUTER JOIN's).
Model definition example:
class BaseModel(models.Model):
foo = models.IntegerField(null=True)
derived = DerivedManager()
class FirstChild(BaseModel):
bar = models.IntegerField(null=True)
class SecondChild(BaseModel):
baz = models.IntegerField(null=True)
How to use:
>>> f = FirstChild.objects.create()
>>> s = SecondChild.objects.create()
>>> print list(BaseModel.objects.all()
[<BaseModel object 1>, <BaseModel object 2>]
>>> print list(BaseModel.derived.all()
[<FirstChild object 1>, <SecondChild object 2>]
>>> print BaseModel.derived.get(pk=s.pk)
<SecondChild object 2>
It's often useful to dynamically create filter criteria, and Q objects are useful for that, but sometimes you need to make a combined Q composed of various alternates. This bit of code eases the awkwardness of creating the first Q so that there's a combiner, plus the odd case of no criteria.
Out of the box, Django e-mail fields for both database models and forms only accept plain e-mail addresses. For example, `[email protected]` is accepted.
On the other hand, full e-mail addresses which include a human-readable name, for example the following address fails validation in Django:
Joe Hacker <[email protected]>
This package adds support for validating full e-mail addresses.
**Database model example**
from django import models
from full_email.models import FullEmailField
class MyModel(models.Model):
email = FullEmailField()
**Forms example**
from django import forms
from full_email.formfields import FullEmailField
class MyForm(forms.Form):
email = FullEmailField(label='E-mail address')
I maintain this code in a [GitHub gist](https://gist.github.com/1505228). It includes some unit tests as well.
Dehydrates objects that can be dictionaries, lists or tuples containing django
model objects or django querysets. For each of those, it creates a
smaller/dehydrated version of it for saving in cache or pickling. The reverse
operation is also provided so dehydrated objects can also be re-hydrated.
*Example:*
>>> import pickle
>>> users = list(User.objects.all()[:20])
>>> print users
[<User: Indiana Jones>, <User: Bilbo Baggins>, ...]
>>> pickled_users = pickle.dumps(users)
>>> print len(pickled_users)
17546
>>> dehydrated_users = dehydrate(users)
>>> pickled_dehydrated_users = pickle.dumps(dehydrated_users)
>>> rehydrated_users = hydrate(pickle.loads(pickled_dehydrated_users))
>>> print rehydrated_users
[<User: Indiana Jones>, <User: Bilbo Baggins>, ...]
>>> print len(pickled_dehydrated_users)
1471
When deleting objects in Django's admin interface, it lists other objects which would be deleted and asks for confirmation. This snippet does the same programmatically.
The snippet works in Django 1.3 (more specifically, revision 14507 or later). It uses Django internals which are not a part of the public API, so this might not work with future versions.
Usage:
`polls/models.py`:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
def __unicode__(self):
return self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
def __unicode__(self):
return '%s %s' % (self.poll, self.choice)
`$ ./manage.py shell`
>>> from polls.models import Poll, Choice
>>> from datetime import datetime
>>> from pprint import pprint
>>> poll1 = Poll.objects.create(question='Me?')
>>> Choice.objects.create(poll=poll1, choice='Yes')
>>> Choice.objects.create(poll=poll1, choice='No')
>>> poll2 = Poll.objects.create(question='Really?')
>>> Choice.objects.create(poll=poll2, choice='Yes')
>>> Choice.objects.create(poll=poll2, choice='No')
>>> pprint(get_related(Poll.objects.all()))
{<class 'polls.models.Poll'>: [<Poll: Me?>, <Poll: Really?>],
<class 'polls.models.Choice'>: [<Choice: Me? Yes>,
<Choice: Me? No>,
<Choice: Really? Yes>,
<Choice: Really? No>]}
Riffing on http://djangosnippets.org/snippets/1024/ I didn't want a graph; I just wanted to see what depended on a specific model.
This does that nicely.
Small changes to [Snippet 1694](http://djangosnippets.org/snippets/1694/) to that QueryAPI works for django 1.2 and higher.
Changes:
* Replaced `get_db_prep_value` with `get_prep_value`.
* Replaced `get_db_prep_lookup` with modified `get_prep_lookup`.