Fix Python – Automatic creation date for Django model form objects

What’s the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated?
models.py:
created_at = models.DateTimeField(False, True, editable=False)
updated_at = models.DateTimeField(True, True, editable=False)

views.py:
if request.method == ‘POST’:
form = MyForm(request.POST)
….

Fix Python – Fastest way to get the first object from a queryset in django?

Often I find myself wanting to get the first object from a queryset in Django, or return None if there aren’t any. There are lots of ways to do this which all work. But I’m wondering which is the most performant.
qs = MyModel.objects.filter(blah = blah)
if qs.count() > 0:
return qs[0]
else:
return None

Does this result in two database c….

Fix Python – Django auto_now and auto_now_add

For Django 1.1.
I have this in my models.py:
class User(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

When updating a row I get:
[Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base.py:84: Warning: Column ‘created’ cannot be n….

Fix Python – Can “list_display” in a Django ModelAdmin display attributes of ForeignKey fields?

I have a Person model that has a foreign key relationship to Book, which has a number of fields, but I’m most concerned about author (a standard CharField).
With that being said, in my PersonAdmin model, I’d like to display book.author using list_display:
class PersonAdmin(admin.ModelAdmin):
list_display = [‘book.author’,]

I’ve tried all of t….

Fix Python – Convert Django Model object to dict with all of the fields intact

How does one convert a django Model object to a dict with all of its fields? All ideally includes foreign keys and fields with editable=False.
Let me elaborate. Let’s say I have a django model like the following:
from django.db import models

class OtherModel(models.Model): pass

class SomeModel(models.Model):
normal_value = models.IntegerFi….

Fix Python – What’s the difference between select_related and prefetch_related in Django ORM?

In Django doc,

select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query.
prefetch_related() does a separate lookup for each relationship, and does the “joining” in Python.

What does it mean by “doing the joining in python”? Can someone illustrate with an example?
My understanding i….