diff --git a/django/contrib/auth/base_user.py b/django/contrib/auth/base_user.py index 7e3161bd98..f39c12a350 100644 --- a/django/contrib/auth/base_user.py +++ b/django/contrib/auth/base_user.py @@ -59,22 +59,22 @@ class AbstractBaseUser(models.Model): class Meta: abstract = True - def get_username(self): - "Return the identifying username for this User" - return getattr(self, self.USERNAME_FIELD) - def __str__(self): return self.get_username() - def clean(self): - setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username())) - def save(self, *args, **kwargs): super().save(*args, **kwargs) if self._password is not None: password_validation.password_changed(self._password, self) self._password = None + def get_username(self): + """Return the username for this User.""" + return getattr(self, self.USERNAME_FIELD) + + def clean(self): + setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username())) + def natural_key(self): return (self.get_username(),) diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py index a144589804..1d40f3f07d 100644 --- a/django/contrib/auth/models.py +++ b/django/contrib/auth/models.py @@ -60,6 +60,7 @@ class Permission(models.Model): verbose_name=_('content type'), ) codename = models.CharField(_('codename'), max_length=100) + objects = PermissionManager() class Meta: diff --git a/django/contrib/gis/db/backends/oracle/models.py b/django/contrib/gis/db/backends/oracle/models.py index 51bed6aa91..6876eecefd 100644 --- a/django/contrib/gis/db/backends/oracle/models.py +++ b/django/contrib/gis/db/backends/oracle/models.py @@ -23,6 +23,9 @@ class OracleGeometryColumns(models.Model): db_table = 'USER_SDO_GEOM_METADATA' managed = False + def __str__(self): + return '%s - %s (SRID: %s)' % (self.table_name, self.column_name, self.srid) + @classmethod def table_name_col(cls): """ @@ -39,9 +42,6 @@ class OracleGeometryColumns(models.Model): """ return 'column_name' - def __str__(self): - return '%s - %s (SRID: %s)' % (self.table_name, self.column_name, self.srid) - class OracleSpatialRefSys(models.Model, SpatialRefSysMixin): "Maps to the Oracle MDSYS.CS_SRS table." diff --git a/django/contrib/gis/db/backends/postgis/models.py b/django/contrib/gis/db/backends/postgis/models.py index 9dd051f885..0cd4d5505c 100644 --- a/django/contrib/gis/db/backends/postgis/models.py +++ b/django/contrib/gis/db/backends/postgis/models.py @@ -23,6 +23,15 @@ class PostGISGeometryColumns(models.Model): db_table = 'geometry_columns' managed = False + def __str__(self): + return '%s.%s - %dD %s field (SRID: %d)' % ( + self.f_table_name, + self.f_geometry_column, + self.coord_dimension, + self.type, + self.srid, + ) + @classmethod def table_name_col(cls): """ @@ -39,11 +48,6 @@ class PostGISGeometryColumns(models.Model): """ return 'f_geometry_column' - def __str__(self): - return "%s.%s - %dD %s field (SRID: %d)" % \ - (self.f_table_name, self.f_geometry_column, - self.coord_dimension, self.type, self.srid) - class PostGISSpatialRefSys(models.Model, SpatialRefSysMixin): """ diff --git a/django/contrib/gis/db/backends/spatialite/models.py b/django/contrib/gis/db/backends/spatialite/models.py index 65cbb33a51..577c7236e3 100644 --- a/django/contrib/gis/db/backends/spatialite/models.py +++ b/django/contrib/gis/db/backends/spatialite/models.py @@ -21,6 +21,15 @@ class SpatialiteGeometryColumns(models.Model): db_table = 'geometry_columns' managed = False + def __str__(self): + return '%s.%s - %dD %s field (SRID: %d)' % ( + self.f_table_name, + self.f_geometry_column, + self.coord_dimension, + self.type, + self.srid, + ) + @classmethod def table_name_col(cls): """ @@ -37,11 +46,6 @@ class SpatialiteGeometryColumns(models.Model): """ return 'f_geometry_column' - def __str__(self): - return "%s.%s - %dD %s field (SRID: %d)" % \ - (self.f_table_name, self.f_geometry_column, - self.coord_dimension, self.type, self.srid) - class SpatialiteSpatialRefSys(models.Model, SpatialRefSysMixin): """ @@ -54,11 +58,11 @@ class SpatialiteSpatialRefSys(models.Model, SpatialRefSysMixin): proj4text = models.CharField(max_length=2048) srtext = models.CharField(max_length=2048) - @property - def wkt(self): - return self.srtext - class Meta: app_label = 'gis' db_table = 'spatial_ref_sys' managed = False + + @property + def wkt(self): + return self.srtext diff --git a/django/contrib/sites/models.py b/django/contrib/sites/models.py index 4e6d3df17a..c8c05a8cf9 100644 --- a/django/contrib/sites/models.py +++ b/django/contrib/sites/models.py @@ -84,6 +84,7 @@ class Site(models.Model): unique=True, ) name = models.CharField(_('display name'), max_length=50) + objects = SiteManager() class Meta: diff --git a/docs/topics/db/examples/many_to_many.txt b/docs/topics/db/examples/many_to_many.txt index 53926d13fe..ed4a093964 100644 --- a/docs/topics/db/examples/many_to_many.txt +++ b/docs/topics/db/examples/many_to_many.txt @@ -17,22 +17,22 @@ objects, and a ``Publication`` has multiple ``Article`` objects: class Publication(models.Model): title = models.CharField(max_length=30) - def __str__(self): - return self.title - class Meta: ordering = ('title',) + def __str__(self): + return self.title + class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) - def __str__(self): - return self.headline - class Meta: ordering = ('headline',) + def __str__(self): + return self.headline + What follows are examples of operations that can be performed using the Python API facilities. Note that if you are using :ref:`an intermediate model ` for a many-to-many relationship, some of the related diff --git a/docs/topics/serialization.txt b/docs/topics/serialization.txt index fba5113e40..e4e92fca43 100644 --- a/docs/topics/serialization.txt +++ b/docs/topics/serialization.txt @@ -404,13 +404,12 @@ name:: return self.get(first_name=first_name, last_name=last_name) class Person(models.Model): - objects = PersonManager() - first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) - birthdate = models.DateField() + objects = PersonManager() + class Meta: unique_together = (('first_name', 'last_name'),) @@ -453,19 +452,18 @@ So how do you get Django to emit a natural key when serializing an object? Firstly, you need to add another method -- this time to the model itself:: class Person(models.Model): - objects = PersonManager() - first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) - birthdate = models.DateField() - def natural_key(self): - return (self.first_name, self.last_name) + objects = PersonManager() class Meta: unique_together = (('first_name', 'last_name'),) + def natural_key(self): + return (self.first_name, self.last_name) + That method should always return a natural key tuple -- in this example, ``(first name, last name)``. Then, when you call ``serializers.serialize()``, you provide ``use_natural_foreign_keys=True`` diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py index 35ba543051..eef8106df4 100644 --- a/tests/admin_views/models.py +++ b/tests/admin_views/models.py @@ -80,13 +80,13 @@ class Chapter(models.Model): content = models.TextField() book = models.ForeignKey(Book, models.CASCADE) - def __str__(self): - return self.title - class Meta: # Use a utf-8 bytestring to ensure it works (see #11710) verbose_name = '¿Chapter?' + def __str__(self): + return self.title + class ChapterXtra1(models.Model): chap = models.OneToOneField(Chapter, models.CASCADE, verbose_name='¿Chap?') diff --git a/tests/admin_widgets/models.py b/tests/admin_widgets/models.py index 5fc9f13e96..b5025fdfd7 100644 --- a/tests/admin_widgets/models.py +++ b/tests/admin_widgets/models.py @@ -135,12 +135,12 @@ class Advisor(models.Model): class Student(models.Model): name = models.CharField(max_length=255) - def __str__(self): - return self.name - class Meta: ordering = ('name',) + def __str__(self): + return self.name + class School(models.Model): name = models.CharField(max_length=255) diff --git a/tests/custom_columns/models.py b/tests/custom_columns/models.py index 32d55af9f3..575ca99a18 100644 --- a/tests/custom_columns/models.py +++ b/tests/custom_columns/models.py @@ -23,13 +23,13 @@ class Author(models.Model): first_name = models.CharField(max_length=30, db_column='firstname') last_name = models.CharField(max_length=30, db_column='last') - def __str__(self): - return '%s %s' % (self.first_name, self.last_name) - class Meta: db_table = 'my_author_table' ordering = ('last_name', 'first_name') + def __str__(self): + return '%s %s' % (self.first_name, self.last_name) + class Article(models.Model): Article_ID = models.AutoField(primary_key=True, db_column='Article ID') @@ -43,8 +43,8 @@ class Article(models.Model): null=True, ) - def __str__(self): - return self.headline - class Meta: ordering = ('headline',) + + def __str__(self): + return self.headline diff --git a/tests/fixtures/models.py b/tests/fixtures/models.py index be6674fa61..fb4fe08f17 100644 --- a/tests/fixtures/models.py +++ b/tests/fixtures/models.py @@ -20,23 +20,23 @@ class Category(models.Model): title = models.CharField(max_length=100) description = models.TextField() - def __str__(self): - return self.title - class Meta: ordering = ('title',) + def __str__(self): + return self.title + class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() - def __str__(self): - return self.headline - class Meta: ordering = ('-pub_date', 'headline') + def __str__(self): + return self.headline + class Blog(models.Model): name = models.CharField(max_length=100) @@ -68,12 +68,12 @@ class Person(models.Model): objects = PersonManager() name = models.CharField(max_length=100) - def __str__(self): - return self.name - class Meta: ordering = ('name',) + def __str__(self): + return self.name + def natural_key(self): return (self.name,) @@ -106,13 +106,13 @@ class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Person) + class Meta: + ordering = ('name',) + def __str__(self): authors = ' and '.join(a.name for a in self.authors.all()) return '%s by %s' % (self.name, authors) if authors else self.name - class Meta: - ordering = ('name',) - class PrimaryKeyUUIDModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) diff --git a/tests/fixtures_model_package/models/__init__.py b/tests/fixtures_model_package/models/__init__.py index 5160f354e6..3e48710fbb 100644 --- a/tests/fixtures_model_package/models/__init__.py +++ b/tests/fixtures_model_package/models/__init__.py @@ -5,9 +5,9 @@ class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() - def __str__(self): - return self.headline - class Meta: app_label = 'fixtures_model_package' ordering = ('-pub_date', 'headline') + + def __str__(self): + return self.headline diff --git a/tests/fixtures_regress/models.py b/tests/fixtures_regress/models.py index d76642ac97..5bc77d9cc9 100644 --- a/tests/fixtures_regress/models.py +++ b/tests/fixtures_regress/models.py @@ -98,10 +98,11 @@ class TestManager(models.Manager): class Store(models.Model): - objects = TestManager() name = models.CharField(max_length=255) main = models.ForeignKey('self', models.SET_NULL, null=True) + objects = TestManager() + class Meta: ordering = ('name',) @@ -113,9 +114,10 @@ class Store(models.Model): class Person(models.Model): - objects = TestManager() name = models.CharField(max_length=255) + objects = TestManager() + class Meta: ordering = ('name',) @@ -245,6 +247,7 @@ class BaseNKModel(models.Model): Base model with a natural_key and a manager with `get_by_natural_key` """ data = models.CharField(max_length=20, unique=True) + objects = NKManager() class Meta: diff --git a/tests/introspection/models.py b/tests/introspection/models.py index 3a494037d2..32acc323bd 100644 --- a/tests/introspection/models.py +++ b/tests/introspection/models.py @@ -41,9 +41,6 @@ class Article(models.Model): response_to = models.ForeignKey('self', models.SET_NULL, null=True) unmanaged_reporters = models.ManyToManyField(Reporter, through='ArticleReporter', related_name='+') - def __str__(self): - return self.headline - class Meta: ordering = ('headline',) index_together = [ @@ -51,6 +48,9 @@ class Article(models.Model): ['headline', 'response_to', 'pub_date', 'reporter'], ] + def __str__(self): + return self.headline + class ArticleReporter(models.Model): article = models.ForeignKey(Article, models.CASCADE) diff --git a/tests/m2m_and_m2o/models.py b/tests/m2m_and_m2o/models.py index 9e3cf7c1da..151f9987f8 100644 --- a/tests/m2m_and_m2o/models.py +++ b/tests/m2m_and_m2o/models.py @@ -15,12 +15,12 @@ class Issue(models.Model): cc = models.ManyToManyField(User, blank=True, related_name='test_issue_cc') client = models.ForeignKey(User, models.CASCADE, related_name='test_issue_client') - def __str__(self): - return str(self.num) - class Meta: ordering = ('num',) + def __str__(self): + return str(self.num) + class StringReferenceModel(models.Model): others = models.ManyToManyField('StringReferenceModel') diff --git a/tests/m2m_regress/models.py b/tests/m2m_regress/models.py index 70966bd0b8..b5148a1714 100644 --- a/tests/m2m_regress/models.py +++ b/tests/m2m_regress/models.py @@ -73,12 +73,12 @@ class User(models.Model): class BadModelWithSplit(models.Model): name = models.CharField(max_length=1) - def split(self): - raise RuntimeError('split should not be called') - class Meta: abstract = True + def split(self): + raise RuntimeError('split should not be called') + class RegressionModelSplit(BadModelWithSplit): """ diff --git a/tests/m2m_through/models.py b/tests/m2m_through/models.py index 5f9fba27a7..a84608a530 100644 --- a/tests/m2m_through/models.py +++ b/tests/m2m_through/models.py @@ -55,13 +55,13 @@ class CustomMembership(models.Model): weird_fk = models.ForeignKey(Membership, models.SET_NULL, null=True) date_joined = models.DateTimeField(default=datetime.now) - def __str__(self): - return "%s is a member of %s" % (self.person.name, self.group.name) - class Meta: db_table = "test_table" ordering = ["date_joined"] + def __str__(self): + return "%s is a member of %s" % (self.person.name, self.group.name) + class TestNoDefaultsOrNulls(models.Model): person = models.ForeignKey(Person, models.CASCADE) diff --git a/tests/m2m_through_regress/models.py b/tests/m2m_through_regress/models.py index 0fd7d9c911..5405e5595c 100644 --- a/tests/m2m_through_regress/models.py +++ b/tests/m2m_through_regress/models.py @@ -52,12 +52,12 @@ class Car(models.Model): class Driver(models.Model): name = models.CharField(max_length=20, unique=True, null=True) - def __str__(self): - return "%s" % self.name - class Meta: ordering = ('name',) + def __str__(self): + return "%s" % self.name + class CarDriver(models.Model): car = models.ForeignKey('Car', models.CASCADE, to_field='make') diff --git a/tests/many_to_many/models.py b/tests/many_to_many/models.py index 7047a4e5d0..a2590b8b36 100644 --- a/tests/many_to_many/models.py +++ b/tests/many_to_many/models.py @@ -12,12 +12,12 @@ from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) - def __str__(self): - return self.title - class Meta: ordering = ('title',) + def __str__(self): + return self.title + class Tag(models.Model): id = models.BigAutoField(primary_key=True) @@ -34,12 +34,12 @@ class Article(models.Model): publications = models.ManyToManyField(Publication, name='publications') tags = models.ManyToManyField(Tag, related_name='tags') - def __str__(self): - return self.headline - class Meta: ordering = ('headline',) + def __str__(self): + return self.headline + # Models to test correct related_name inheritance class AbstractArticle(models.Model): diff --git a/tests/many_to_one/models.py b/tests/many_to_one/models.py index ef784cfbe2..96b84ccddb 100644 --- a/tests/many_to_one/models.py +++ b/tests/many_to_one/models.py @@ -20,12 +20,12 @@ class Article(models.Model): pub_date = models.DateField() reporter = models.ForeignKey(Reporter, models.CASCADE) - def __str__(self): - return self.headline - class Meta: ordering = ('headline',) + def __str__(self): + return self.headline + class City(models.Model): id = models.BigAutoField(primary_key=True) diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py index 2c67c187cf..5a80243574 100644 --- a/tests/model_forms/models.py +++ b/tests/model_forms/models.py @@ -215,12 +215,12 @@ class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField() - def __str__(self): - return "%s for %s" % (self.quantity, self.price) - class Meta: unique_together = (('price', 'quantity'),) + def __str__(self): + return "%s for %s" % (self.quantity, self.price) + class Triple(models.Model): left = models.IntegerField() diff --git a/tests/model_formsets/models.py b/tests/model_formsets/models.py index 92a07e010f..72728ec582 100644 --- a/tests/model_formsets/models.py +++ b/tests/model_formsets/models.py @@ -135,12 +135,12 @@ class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField() - def __str__(self): - return "%s for %s" % (self.quantity, self.price) - class Meta: unique_together = (('price', 'quantity'),) + def __str__(self): + return "%s for %s" % (self.quantity, self.price) + class MexicanRestaurant(Restaurant): serves_tacos = models.BooleanField(default=False) diff --git a/tests/multiple_database/models.py b/tests/multiple_database/models.py index 14cb946f62..5d1251ecb3 100644 --- a/tests/multiple_database/models.py +++ b/tests/multiple_database/models.py @@ -12,12 +12,12 @@ class Review(models.Model): object_id = models.PositiveIntegerField() content_object = GenericForeignKey() - def __str__(self): - return self.source - class Meta: ordering = ('source',) + def __str__(self): + return self.source + class PersonManager(models.Manager): def get_by_natural_key(self, name): @@ -25,15 +25,16 @@ class PersonManager(models.Manager): class Person(models.Model): - objects = PersonManager() name = models.CharField(max_length=100) - def __str__(self): - return self.name + objects = PersonManager() class Meta: ordering = ('name',) + def __str__(self): + return self.name + # This book manager doesn't do anything interesting; it just # exists to strip out the 'extra_arg' argument to certain @@ -48,7 +49,6 @@ class BookManager(models.Manager): class Book(models.Model): - objects = BookManager() title = models.CharField(max_length=100) published = models.DateField() authors = models.ManyToManyField(Person) @@ -56,23 +56,25 @@ class Book(models.Model): reviews = GenericRelation(Review) pages = models.IntegerField(default=100) - def __str__(self): - return self.title + objects = BookManager() class Meta: ordering = ('title',) + def __str__(self): + return self.title + class Pet(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(Person, models.CASCADE) - def __str__(self): - return self.name - class Meta: ordering = ('name',) + def __str__(self): + return self.name + class UserProfile(models.Model): user = models.OneToOneField(User, models.SET_NULL, null=True) diff --git a/tests/null_fk_ordering/models.py b/tests/null_fk_ordering/models.py index 368a47044e..82f3fed9f9 100644 --- a/tests/null_fk_ordering/models.py +++ b/tests/null_fk_ordering/models.py @@ -17,12 +17,12 @@ class Article(models.Model): title = models.CharField(max_length=150) author = models.ForeignKey(Author, models.SET_NULL, null=True) - def __str__(self): - return 'Article titled: %s' % self.title - class Meta: ordering = ['author__name'] + def __str__(self): + return 'Article titled: %s' % self.title + # These following 4 models represent a far more complex ordering case. class SystemInfo(models.Model): diff --git a/tests/prefetch_related/models.py b/tests/prefetch_related/models.py index cb64b52a15..091d600475 100644 --- a/tests/prefetch_related/models.py +++ b/tests/prefetch_related/models.py @@ -15,12 +15,12 @@ class Author(models.Model): favorite_authors = models.ManyToManyField( 'self', through='FavoriteAuthors', symmetrical=False, related_name='favors_me') - def __str__(self): - return self.name - class Meta: ordering = ['id'] + def __str__(self): + return self.name + class AuthorWithAge(Author): author = models.OneToOneField(Author, models.CASCADE, parent_link=True) @@ -50,12 +50,12 @@ class Book(models.Model): title = models.CharField(max_length=255) authors = models.ManyToManyField(Author, related_name='books') - def __str__(self): - return self.title - class Meta: ordering = ['id'] + def __str__(self): + return self.title + class BookWithYear(Book): book = models.OneToOneField(Book, models.CASCADE, parent_link=True) @@ -78,12 +78,12 @@ class Reader(models.Model): name = models.CharField(max_length=50) books_read = models.ManyToManyField(Book, related_name='read_by') - def __str__(self): - return self.name - class Meta: ordering = ['id'] + def __str__(self): + return self.name + class BookReview(models.Model): # Intentionally does not have a related name. @@ -122,12 +122,12 @@ class Teacher(models.Model): objects = TeacherManager() objects_custom = TeacherQuerySet.as_manager() - def __str__(self): - return "%s (%s)" % (self.name, ", ".join(q.name for q in self.qualifications.all())) - class Meta: ordering = ['id'] + def __str__(self): + return "%s (%s)" % (self.name, ", ".join(q.name for q in self.qualifications.all())) + class Department(models.Model): name = models.CharField(max_length=50) @@ -165,12 +165,12 @@ class TaggedItem(models.Model): favorite_fkey = models.CharField(max_length=64, null=True) favorite = GenericForeignKey('favorite_ct', 'favorite_fkey') - def __str__(self): - return self.tag - class Meta: ordering = ['id'] + def __str__(self): + return self.tag + class Bookmark(models.Model): url = models.URLField() @@ -243,12 +243,12 @@ class Employee(models.Model): name = models.CharField(max_length=50) boss = models.ForeignKey('self', models.SET_NULL, null=True, related_name='serfs') - def __str__(self): - return self.name - class Meta: ordering = ['id'] + def __str__(self): + return self.name + # Ticket #19607 @@ -275,12 +275,12 @@ class Author2(models.Model): first_book = models.ForeignKey('Book', models.CASCADE, related_name='first_time_authors+') favorite_books = models.ManyToManyField('Book', related_name='+') - def __str__(self): - return self.name - class Meta: ordering = ['id'] + def __str__(self): + return self.name + # Models for many-to-many with UUID pk test: diff --git a/tests/serializers/models/natural.py b/tests/serializers/models/natural.py index 62cf95185e..8f0bc48648 100644 --- a/tests/serializers/models/natural.py +++ b/tests/serializers/models/natural.py @@ -10,11 +10,11 @@ class NaturalKeyAnchorManager(models.Manager): class NaturalKeyAnchor(models.Model): - objects = NaturalKeyAnchorManager() - data = models.CharField(max_length=100, unique=True) title = models.CharField(max_length=100, null=True) + objects = NaturalKeyAnchorManager() + def natural_key(self): return (self.data,)