models.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """
  2. Custom column/table names
  3. If your database column name is different than your model attribute, use the
  4. ``db_column`` parameter. Note that you'll use the field's name, not its column
  5. name, in API usage.
  6. If your database table name is different than your model name, use the
  7. ``db_table`` Meta attribute. This has no effect on the API used to
  8. query the database.
  9. If you need to use a table name for a many-to-many relationship that differs
  10. from the default generated name, use the ``db_table`` parameter on the
  11. ``ManyToManyField``. This has no effect on the API for querying the database.
  12. """
  13. from __future__ import unicode_literals
  14. from django.db import models
  15. from django.utils.encoding import python_2_unicode_compatible
  16. @python_2_unicode_compatible
  17. class Author(models.Model):
  18. Author_ID = models.AutoField(primary_key=True, db_column='Author ID')
  19. first_name = models.CharField(max_length=30, db_column='firstname')
  20. last_name = models.CharField(max_length=30, db_column='last')
  21. def __str__(self):
  22. return '%s %s' % (self.first_name, self.last_name)
  23. class Meta:
  24. db_table = 'my_author_table'
  25. ordering = ('last_name', 'first_name')
  26. @python_2_unicode_compatible
  27. class Article(models.Model):
  28. Article_ID = models.AutoField(primary_key=True, db_column='Article ID')
  29. headline = models.CharField(max_length=100)
  30. authors = models.ManyToManyField(Author, db_table='my_m2m_table')
  31. primary_author = models.ForeignKey(
  32. Author,
  33. models.SET_NULL,
  34. db_column='Author ID',
  35. related_name='primary_set',
  36. null=True,
  37. )
  38. def __str__(self):
  39. return self.headline
  40. class Meta:
  41. ordering = ('headline',)