2007-09-14 20:36:04 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
2006-05-02 03:31:56 +02:00
|
|
|
"""
|
|
|
|
14. Using a custom primary key
|
|
|
|
|
|
|
|
By default, Django adds an ``"id"`` field to each model. But you can override
|
|
|
|
this behavior by explicitly adding ``primary_key=True`` to a field.
|
|
|
|
"""
|
|
|
|
|
2013-07-29 19:19:04 +02:00
|
|
|
from __future__ import unicode_literals
|
2011-10-13 20:04:12 +02:00
|
|
|
|
2011-07-13 11:35:51 +02:00
|
|
|
from django.db import models
|
2006-05-02 03:31:56 +02:00
|
|
|
|
2011-10-13 20:04:12 +02:00
|
|
|
from .fields import MyAutoField
|
2012-08-12 12:32:08 +02:00
|
|
|
from django.utils.encoding import python_2_unicode_compatible
|
2011-10-13 20:04:12 +02:00
|
|
|
|
2009-06-08 06:50:24 +02:00
|
|
|
|
2012-08-12 12:32:08 +02:00
|
|
|
@python_2_unicode_compatible
|
2006-05-02 03:31:56 +02:00
|
|
|
class Employee(models.Model):
|
2008-09-03 02:09:33 +02:00
|
|
|
employee_code = models.IntegerField(primary_key=True, db_column = 'code')
|
2007-08-05 07:14:46 +02:00
|
|
|
first_name = models.CharField(max_length=20)
|
|
|
|
last_name = models.CharField(max_length=20)
|
2006-05-02 03:31:56 +02:00
|
|
|
class Meta:
|
|
|
|
ordering = ('last_name', 'first_name')
|
|
|
|
|
2012-08-12 12:32:08 +02:00
|
|
|
def __str__(self):
|
2012-06-07 18:08:47 +02:00
|
|
|
return "%s %s" % (self.first_name, self.last_name)
|
2006-05-02 03:31:56 +02:00
|
|
|
|
2012-08-12 12:32:08 +02:00
|
|
|
@python_2_unicode_compatible
|
2006-05-02 03:31:56 +02:00
|
|
|
class Business(models.Model):
|
2007-08-05 07:14:46 +02:00
|
|
|
name = models.CharField(max_length=20, primary_key=True)
|
2006-05-02 03:31:56 +02:00
|
|
|
employees = models.ManyToManyField(Employee)
|
|
|
|
class Meta:
|
|
|
|
verbose_name_plural = 'businesses'
|
|
|
|
|
2012-08-12 12:32:08 +02:00
|
|
|
def __str__(self):
|
2006-05-02 03:31:56 +02:00
|
|
|
return self.name
|
|
|
|
|
2012-08-12 12:32:08 +02:00
|
|
|
@python_2_unicode_compatible
|
2009-06-08 06:50:24 +02:00
|
|
|
class Bar(models.Model):
|
|
|
|
id = MyAutoField(primary_key=True, db_index=True)
|
|
|
|
|
2012-08-12 12:32:08 +02:00
|
|
|
def __str__(self):
|
2009-06-08 06:50:24 +02:00
|
|
|
return repr(self.pk)
|
|
|
|
|
|
|
|
|
|
|
|
class Foo(models.Model):
|
|
|
|
bar = models.ForeignKey(Bar)
|