mirror of https://github.com/django/django.git
Refs #26678 -- Added tests for using the field the relation points to with RelatedManager.add()/remove()/set().
This commit is contained in:
parent
a44a21a22f
commit
0e2ed4fdd1
|
@ -38,6 +38,7 @@ class Article(models.Model):
|
|||
# correctly created. Refs #20207
|
||||
publications = models.ManyToManyField(Publication, name='publications')
|
||||
tags = models.ManyToManyField(Tag, related_name='tags')
|
||||
authors = models.ManyToManyField('User', through='UserArticle')
|
||||
|
||||
objects = NoDeletedArticleManager()
|
||||
|
||||
|
@ -48,6 +49,18 @@ class Article(models.Model):
|
|||
return self.headline
|
||||
|
||||
|
||||
class User(models.Model):
|
||||
username = models.CharField(max_length=20, unique=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.username
|
||||
|
||||
|
||||
class UserArticle(models.Model):
|
||||
user = models.ForeignKey(User, models.CASCADE, to_field='username')
|
||||
article = models.ForeignKey(Article, models.CASCADE)
|
||||
|
||||
|
||||
# Models to test correct related_name inheritance
|
||||
class AbstractArticle(models.Model):
|
||||
class Meta:
|
||||
|
|
|
@ -3,7 +3,9 @@ from unittest import mock
|
|||
from django.db import transaction
|
||||
from django.test import TestCase, skipUnlessDBFeature
|
||||
|
||||
from .models import Article, InheritedArticleA, InheritedArticleB, Publication
|
||||
from .models import (
|
||||
Article, InheritedArticleA, InheritedArticleB, Publication, User,
|
||||
)
|
||||
|
||||
|
||||
class ManyToManyTests(TestCase):
|
||||
|
@ -76,6 +78,32 @@ class ManyToManyTests(TestCase):
|
|||
]
|
||||
)
|
||||
|
||||
def test_add_remove_set_by_pk(self):
|
||||
a5 = Article.objects.create(headline='Django lets you create Web apps easily')
|
||||
a5.publications.add(self.p1.pk)
|
||||
self.assertQuerysetEqual(
|
||||
a5.publications.all(),
|
||||
['<Publication: The Python Journal>'],
|
||||
)
|
||||
a5.publications.set([self.p2.pk])
|
||||
self.assertQuerysetEqual(
|
||||
a5.publications.all(),
|
||||
['<Publication: Science News>'],
|
||||
)
|
||||
a5.publications.remove(self.p2.pk)
|
||||
self.assertQuerysetEqual(a5.publications.all(), [])
|
||||
|
||||
def test_add_remove_set_by_to_field(self):
|
||||
user_1 = User.objects.create(username='Jean')
|
||||
user_2 = User.objects.create(username='Joe')
|
||||
a5 = Article.objects.create(headline='Django lets you create Web apps easily')
|
||||
a5.authors.add(user_1.username)
|
||||
self.assertQuerysetEqual(a5.authors.all(), ['<User: Jean>'])
|
||||
a5.authors.set([user_2.username])
|
||||
self.assertQuerysetEqual(a5.authors.all(), ['<User: Joe>'])
|
||||
a5.authors.remove(user_2.username)
|
||||
self.assertQuerysetEqual(a5.authors.all(), [])
|
||||
|
||||
def test_reverse_add(self):
|
||||
# Adding via the 'other' end of an m2m
|
||||
a5 = Article(headline='NASA finds intelligent life on Mars')
|
||||
|
|
Loading…
Reference in New Issue