2
17. Custom column/table names
4
If your database column name is different than your model attribute, use the
5
``db_column`` parameter. Note that you'll use the field's name, not its column
8
If your database table name is different than your model name, use the
9
``db_table`` Meta attribute. This has no effect on the API used to
12
If you need to use a table name for a many-to-many relationship that differs
13
from the default generated name, use the ``db_table`` parameter on the
14
``ManyToManyField``. This has no effect on the API for querying the database.
18
from django.db import models
20
class Author(models.Model):
21
first_name = models.CharField(max_length=30, db_column='firstname')
22
last_name = models.CharField(max_length=30, db_column='last')
24
def __unicode__(self):
25
return u'%s %s' % (self.first_name, self.last_name)
28
db_table = 'my_author_table'
29
ordering = ('last_name','first_name')
31
class Article(models.Model):
32
headline = models.CharField(max_length=100)
33
authors = models.ManyToManyField(Author, db_table='my_m2m_table')
35
def __unicode__(self):
39
ordering = ('headline',)
41
__test__ = {'API_TESTS':"""
43
>>> a = Author(first_name='John', last_name='Smith')
49
# Create another author
50
>>> a2 = Author(first_name='Peter', last_name='Jones')
54
>>> art = Article(headline='Django lets you build web apps easily')
56
>>> art.authors = [a, a2]
58
# Although the table and column names on Author have been set to custom values,
59
# nothing about using the Author model has changed...
61
# Query the available authors
62
>>> Author.objects.all()
63
[<Author: Peter Jones>, <Author: John Smith>]
65
>>> Author.objects.filter(first_name__exact='John')
66
[<Author: John Smith>]
68
>>> Author.objects.get(first_name__exact='John')
71
>>> Author.objects.filter(firstname__exact='John')
72
Traceback (most recent call last):
74
FieldError: Cannot resolve keyword 'firstname' into field. Choices are: article, first_name, id, last_name
76
>>> a = Author.objects.get(last_name__exact='Smith')
82
Traceback (most recent call last):
84
AttributeError: 'Author' object has no attribute 'firstname'
86
Traceback (most recent call last):
88
AttributeError: 'Author' object has no attribute 'last'
90
# Although the Article table uses a custom m2m table,
91
# nothing about using the m2m relationship has changed...
93
# Get all the authors for an article
95
[<Author: Peter Jones>, <Author: John Smith>]
97
# Get the articles for an author
98
>>> a.article_set.all()
99
[<Article: Django lets you build web apps easily>]
101
# Query the authors across the m2m relation
102
>>> art.authors.filter(last_name='Jones')
103
[<Author: Peter Jones>]