2
14. Using a custom primary key
4
By default, Django adds an ``"id"`` field to each model. But you can override
5
this behavior by explicitly adding ``primary_key=True`` to a field.
8
from django.db import models
10
class Employee(models.Model):
11
employee_code = models.CharField(maxlength=10, primary_key=True)
12
first_name = models.CharField(maxlength=20)
13
last_name = models.CharField(maxlength=20)
15
ordering = ('last_name', 'first_name')
18
return "%s %s" % (self.first_name, self.last_name)
20
class Business(models.Model):
21
name = models.CharField(maxlength=20, primary_key=True)
22
employees = models.ManyToManyField(Employee)
24
verbose_name_plural = 'businesses'
30
>>> dan = Employee(employee_code='ABC123', first_name='Dan', last_name='Jones')
32
>>> Employee.objects.all()
35
>>> fran = Employee(employee_code='XYZ456', first_name='Fran', last_name='Bones')
37
>>> Employee.objects.all()
38
[Fran Bones, Dan Jones]
40
>>> Employee.objects.get(pk='ABC123')
42
>>> Employee.objects.get(pk='XYZ456')
44
>>> Employee.objects.get(pk='foo')
45
Traceback (most recent call last):
47
DoesNotExist: Employee does not exist for {'pk': 'foo'}
49
# Use the name of the primary key, rather than pk.
50
>>> Employee.objects.get(employee_code__exact='ABC123')
53
# Fran got married and changed her last name.
54
>>> fran = Employee.objects.get(pk='XYZ456')
55
>>> fran.last_name = 'Jones'
57
>>> Employee.objects.filter(last_name__exact='Jones')
58
[Dan Jones, Fran Jones]
59
>>> Employee.objects.in_bulk(['ABC123', 'XYZ456'])
60
{'XYZ456': Fran Jones, 'ABC123': Dan Jones}
62
>>> b = Business(name='Sears')
64
>>> b.employees.add(dan, fran)
66
[Dan Jones, Fran Jones]
67
>>> fran.business_set.all()
69
>>> Business.objects.in_bulk(['Sears'])
72
>>> Business.objects.filter(name__exact='Sears')
74
>>> Business.objects.filter(pk='Sears')
77
# Queries across tables, involving primary key
78
>>> Employee.objects.filter(business__name__exact='Sears')
79
[Dan Jones, Fran Jones]
80
>>> Employee.objects.filter(business__pk='Sears')
81
[Dan Jones, Fran Jones]
83
>>> Business.objects.filter(employees__employee_code__exact='ABC123')
85
>>> Business.objects.filter(employees__pk='ABC123')
87
>>> Business.objects.filter(employees__first_name__startswith='Fran')