2006-05-02 09:31:56 +08:00
|
|
|
"""
|
2014-09-24 13:13:13 +08:00
|
|
|
Many-to-many relationships
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2008-08-12 22:15:38 +08:00
|
|
|
To define a many-to-many relationship, use ``ManyToManyField()``.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2008-08-12 22:15:38 +08:00
|
|
|
In this example, an ``Article`` can be published in multiple ``Publication``
|
|
|
|
objects, and a ``Publication`` has multiple ``Article`` objects.
|
2006-05-02 09:31:56 +08:00
|
|
|
"""
|
2013-04-06 01:59:15 +08:00
|
|
|
from __future__ import unicode_literals
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
from django.db import models
|
2012-08-12 18:32:08 +08:00
|
|
|
from django.utils.encoding import python_2_unicode_compatible
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2011-10-14 02:04:12 +08:00
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
@python_2_unicode_compatible
|
2006-05-02 09:31:56 +08:00
|
|
|
class Publication(models.Model):
|
2007-08-05 13:14:46 +08:00
|
|
|
title = models.CharField(max_length=30)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
def __str__(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
return self.title
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ('title',)
|
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
@python_2_unicode_compatible
|
2006-05-02 09:31:56 +08:00
|
|
|
class Article(models.Model):
|
2007-08-05 13:14:46 +08:00
|
|
|
headline = models.CharField(max_length=100)
|
2013-04-06 01:59:15 +08:00
|
|
|
# Assign a unicode string as name to make sure the intermediary model is
|
|
|
|
# correctly created. Refs #20207
|
|
|
|
publications = models.ManyToManyField(Publication, name='publications')
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
def __str__(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
return self.headline
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ('headline',)
|