This manager is intended for use with models with publication and/or expiration dates. Objects will be retrieved only if their publication and/or expiration dates are within the current date.
Use is very simple:
class ExampleModel(models.Model):
publish_date = models.DateTimeField()
expire_date = models.DateTimeField(blank=True, null=True)
objects = models.Manager()
actives = ActiveManager(from_date='publish_date', to_date='expire_date')
ExampleModel.actives.all() # retrieve active objects according to the current date
The manager works correctly with nullable date fields. A null publication date means "*always published (until expiration date)*" and a null expiration date means "*never expires*".
Most models should define the `objects` manager as the default manager, because otherwise out of date objects won't appear in the admin app.
Sometimes you need to prevent concurrent access to update/calculate some properties right. Here is (MySQL) specific example to lock one table with new object manager functions.
RowCacheManager is a model manager that will try to fetch any 'get' (i.e., single-row) requests from the cache. ModelWithCaching is an abstract base model that does some extra work that you'll probably want if you're using the RowCacheManager. So to use this code, you just need to do two things: First, set objects=RowCacheManager() in your model definition, then inherit from ModelWithCaching if you want the invalidation for free. If you are unusually brave, use the metaclass for ModelWithCaching and you won't even need the "objects=RowCacheManager()" line.
An abstract model base class that gives your models a random base-32 string ID. This can be useful in many ways. Requires a Django version recent enough to support model inheritance.
I needed an abstract base class that can add attributes to the child classes based on the child's name. The attributes had to be implicit, but overridable, so all derived classes would get them by default, but they could be easily overriden in the child definition.
So, the code code I came up with basically consists of a customized metaclass used by the abstract model.
This class will automatically create a django choices tuple like this:
STATUS_CHOICES = django_choices(Draft=1, Public=2, Closed=3)
Additionally, it includes a method that converts the choices tuple to a dictionary. Like this:
STATUS = STATUS_CHOICES.to_dict()
Those types can come in handy when you need to use those magic values in your code. Best done within the model once so everyone can use it. Code based on: http://www.djangosnippets.org/snippets/455/.
By the way, if you want to just have the method without having to convert to the newer syntax.. it's backward compatible. Just add django_choices in front of the first paren for your choices tuple.
Django supports the serializing model objects, but does not support the serializing Q object like that,
============================
q = Q(username__contains="findme")
model0.objects.filter(q)
serialize(q) # X
============================
so I wrote a little marshaller for Q, this is example,
============================
from django.contrib.auth import models as django_models
qs = django_query.Q(username__contains="spike") | django_query.Q(email__contains="spike")
_m = QMarshaller()
a = _m.dumps(qs) # a was serialized.
When call the similiar queries in page by page, you don't need to write additional code for creating same Q(s) for filtering models, just use the serialized Q as http querystring and in the next page unserialize and apply it. That is simple life.
This snippet creates thumbnails on-demand from a ImageField with any size using dynamics methods, like ``get_photo_80x80_url`` or ``get_photo_640x480_filename``, etc.
It assumes you have an `ImageField` in your Model called `photo` and have this in your models.py:
import re
from os import path
from PIL import Image
GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$')
`models.py` example:
import re
from os import path
from PIL import Image
from django.db import models
GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$')
class Photo(models.Model):
photo = models.ImageField(upload_to='photos/%Y/%m/%d')
<snippet here>
Example usage:
>>> photo = Photo(photo="/tmp/test.jpg")
>>> photo.save()
>>> photo.get_photo_80x80_url()
u"http://media.example.net/photos/2008/02/26/test_80x80.jpg"
>>> photo.get_photo_80x80_filename()
u"/srv/media/photos/2008/02/26/test_80x80.jpg"
>>> photo.get_photo_64x64_url()
u"http://media.example.net/photos/2008/02/26/test_64x64.jpg"
>>> photo.get_photo_64x64_filename()
u"/srv/media/photos/2008/02/26/test_64x64.jpg"
This is a little improvement to the [idea](http://www.djangosnippets.org/snippets/540/) from sheats a few days ago.
I like it over the previous solutions because it doesn't involve doing anything other than running `./manage.py shell` inside your project directory. You don't have to create any files anywhere or remember to call anything, and `ipython` still works fine outside of a Django project.
Throw this code in `~/.ipython/ipy_user_conf.py` (`ipythonrc` has apparently been deprecated).
*Incredibly useful for storing just about anything in the database (provided it is Pickle-able, of course) when there isn't a 'proper' field for the job:*
A field which can store any pickleable object in the database. It is database-agnostic, and should work with any database backend you can throw at it.
Pass in any object and it will be automagically converted behind the scenes, and you never have to manually pickle or unpickle anything. Also works fine when querying.
**Please note that this is supposed to be two files, one fields.py and one tests.py (if you don't care about the unit tests, just use fields.py)**
This is a little helper for associating an owner to a newly created object, in this case making the assumption that the current user is always the owner. It removes the necessity of adding a custom save hook to your model.
get_current_user comes from this middleware trick to cache the current user:
http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
I had a problem: too many fetches from the DB.
So, how to reduce load on the database without major changes to the code?
Cache Manager is the answer. I've managed to reduce number of DB hits as much as 80% in some cases (dictionaries, complex relations). It is using standard cache mechanisms. I'm using it with mathopd.
This is a very simple solution, instead of standard Manager, put this in your model definition as:
`objects = CacheManager()`
Then everythere elase in the code instead of all() or get(...) call all_cached() or get_cached().
I've kept original methods intact, to have an dual access, when you really, really must have frest data from the DB, and you can't wait for cache to expire.
This is much easier to work with, then manually getting fetched data from the cache.No change to your existing code 9except model) and voila!
Additionally if you have some data, you would like to store with your serialized object (e.g. related data, dynamic dictionaries), you can do this in the model method '_init_instance_cache').
Drop me an email if you find this useful. :)
Based on the UPDATE query section of `Model.save()`, this is another means of limiting the fields which are used in an UPDATE statement and bypassing the check for object existence which is made when you use `Model.save()`.
Just make whatever changes you want to your model instance and call `update`, passing your instance and the names of any fields to be updated.
Usage example:
import datetime
from forum.models import Topic
from forum.utils.models import update
topic = Topic.objects.get(pk=1)
topic.post_count += 1
topic.last_post_at = datetime.datetime.now()
update(topic, 'post_count', 'last_post_at')
(Originally intended as a comment on [Snippet 479](/snippets/479/), but comments aren't working for me)