| 1 |
""" |
| 2 |
Many-to-many relationships |
| 3 |
|
| 4 |
To define a many-to-many relationship, use ``ManyToManyField()``. |
| 5 |
|
| 6 |
In this example, an ``Article`` can be published in multiple ``Publication`` |
| 7 |
objects, and a ``Publication`` has multiple ``Article`` objects. |
| 8 |
""" |
| 9 |
|
| 10 |
from django.db import models |
| 11 |
|
| 12 |
|
| 13 |
class Publication(models.Model): |
| 14 |
title = models.CharField(max_length=30) |
| 15 |
|
| 16 |
class Meta: |
| 17 |
ordering = ("title",) |
| 18 |
|
| 19 |
def __str__(self): |
| 20 |
return self.title |
| 21 |
|
| 22 |
|
| 23 |
class Tag(models.Model): |
| 24 |
id = models.BigAutoField(primary_key=True) |
| 25 |
name = models.CharField(max_length=50) |
| 26 |
|
| 27 |
def __str__(self): |
| 28 |
return self.name |
| 29 |
|
| 30 |
|
| 31 |
class NoDeletedArticleManager(models.Manager): |
| 32 |
def get_queryset(self): |
| 33 |
return super().get_queryset().exclude(headline="deleted") |
| 34 |
|
| 35 |
|
| 36 |
class Article(models.Model): |
| 37 |
headline = models.CharField(max_length=100) |
| 38 |
# Assign a string as name to make sure the intermediary model is |
| 39 |
# correctly created. Refs #20207 |
| 40 |
publications = models.ManyToManyField(Publication, name="publications") |
| 41 |
tags = models.ManyToManyField(Tag, related_name="tags") |
| 42 |
authors = models.ManyToManyField("User", through="UserArticle") |
| 43 |
|
| 44 |
objects = NoDeletedArticleManager() |
| 45 |
|
| 46 |
class Meta: |
| 47 |
ordering = ("headline",) |
| 48 |
|
| 49 |
def __str__(self): |
| 50 |
return self.headline |
| 51 |
|
| 52 |
|
| 53 |
class User(models.Model): |
| 54 |
username = models.CharField(max_length=20, unique=True) |
| 55 |
|
| 56 |
def __str__(self): |
| 57 |
return self.username |
| 58 |
|
| 59 |
|
| 60 |
class UserArticle(models.Model): |
| 61 |
user = models.ForeignKey(User, models.CASCADE, to_field="username") |
| 62 |
article = models.ForeignKey(Article, models.CASCADE) |
| 63 |
|
| 64 |
|
| 65 |
# Models to test correct related_name inheritance |
| 66 |
class AbstractArticle(models.Model): |
| 67 |
class Meta: |
| 68 |
abstract = True |
| 69 |
|
| 70 |
publications = models.ManyToManyField( |
| 71 |
Publication, name="publications", related_name="+" |
| 72 |
) |
| 73 |
|
| 74 |
|
| 75 |
class InheritedArticleA(AbstractArticle): |
| 76 |
pass |
| 77 |
|
| 78 |
|
| 79 |
class InheritedArticleB(AbstractArticle): |
| 80 |
pass |
| 81 |
|
| 82 |
|
| 83 |
class NullableTargetArticle(models.Model): |
| 84 |
headline = models.CharField(max_length=100) |
| 85 |
publications = models.ManyToManyField( |
| 86 |
Publication, through="NullablePublicationThrough" |
| 87 |
) |
| 88 |
|
| 89 |
|
| 90 |
class NullablePublicationThrough(models.Model): |
| 91 |
article = models.ForeignKey(NullableTargetArticle, models.CASCADE) |
| 92 |
publication = models.ForeignKey(Publication, models.CASCADE, null=True) |