Django Code Snipets - WBowam/wbowam.github.com GitHub Wiki

Date:2015-07-07
Title: Django 知识碎片
Tags: Django, Snippets
Category:IT

我写了一段如此恶心的代码:
channels = Channel.objects.all()
for item in channels:
    item.star_levels = 6
    item.save()

正确写法:

channels = Channel.objects.all()
channels.update(star_level=6)
django model 中create_time and datetime的最佳方案

之前用django datetime过程中各种揪心

于是,决定用如下方案

import datetime

class User(models.Model):
    created     = models.DateTimeField(editable=False)
    modified    = models.DateTimeField()

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        if not self.id:
            self.created = datetime.datetime.today()
        self.modified = datetime.datetime.today()
        return super(User, self).save(*args, **kwargs)

django 用migrate新加字段

## Initialize migrations for your existing models:
./manage.py makemigrations myapp

## Fake migrations for existing models:
./manage.py migrate --fake myapp

## Add the new field to myapp.models:
from django.db import models

class MyModel(models.Model):
... #existing fields
newfield = models.CharField(max_length=100) #new field

##Run makemigrations again (this will add a new migration file in migrations folder that add the newfield to db):
./manage.py makemigrations myapp
## Run migrate again:

./manage.py migrate myapp
fields = model._meta.fields()
blank = [f.blank for f in fields]
model._meta.get_field('g').get_internal_type

django admin short_description

You have four possible values that can be used in list_display:

A field of the model. For example:

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name')

A callable that accepts one parameter for the model instance. For example:

def upper_case_name(obj):
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'

class PersonAdmin(admin.ModelAdmin):
    list_display = (upper_case_name,)

A string representing an attribute on the ModelAdmin. This behaves same as the callable. For example:

class PersonAdmin(admin.ModelAdmin):
    list_display = ('upper_case_name',)

    def upper_case_name(self, obj):
        return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    upper_case_name.short_description = 'Name'

打出mysql语句

print queryset.query

django unique tegother

class Meta:
    unique_together = ('english_name', 'chinese_name', 'state',)
    ordering = ['id', ]

django cache demo

from django.core.cache import cache
## The basic interface is set(key, value, timeout) and get(key): 
## set(key, value, timeout)
## You can set TIMEOUT to None so that, by default, cache keys never expire
cache.set('my_key', 'hello, world!')
cache.set("experience_feedback_job", past_ids, 60) ## expire 60 in seconds
past_ids = cache.get("experience_feedback_job", [])
## settings.py
CACHES = {
    # act as memcache
    'default': {
        'BACKEND': 'redis_cache.cache.RedisCache',
        'LOCATION': '127.0.0.1:6379:0',
        'OPTIONS': {
            'PASSWORD': '',  # Optional
            'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
            'PARSER_CLASS': 'redis.connection.HiredisParser',
            'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool',
            'CONNECTION_POOL_CLASS_KWARGS': {
                'max_connections': 500,
                'timeout': 10,
            }
        }
    },
}

django email alias

send_mail('subject', 'message', 'Dont Reply <[email protected]>', ['[email protected]’])