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?
created_at = models.DateTimeField(False, True, editable=False)
updated_at = models.DateTimeField(True, True, editable=False)
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]
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
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/ 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 using list_display:
class PersonAdmin(admin.ModelAdmin):
list_display = [‘’,]

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….