From 0e2ed4fdd197dae1da2553111034e92e10b30c41 Mon Sep 17 00:00:00 2001 From: Tobias Kunze Date: Fri, 3 May 2019 19:47:53 +0200 Subject: [PATCH] Refs #26678 -- Added tests for using the field the relation points to with RelatedManager.add()/remove()/set(). --- tests/many_to_many/models.py | 13 +++++++++++++ tests/many_to_many/tests.py | 30 +++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/tests/many_to_many/models.py b/tests/many_to_many/models.py index 7b46d2484e..49aa73144f 100644 --- a/tests/many_to_many/models.py +++ b/tests/many_to_many/models.py @@ -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: diff --git a/tests/many_to_many/tests.py b/tests/many_to_many/tests.py index 7434d18e02..8ff1185878 100644 --- a/tests/many_to_many/tests.py +++ b/tests/many_to_many/tests.py @@ -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(), + [''], + ) + a5.publications.set([self.p2.pk]) + self.assertQuerysetEqual( + a5.publications.all(), + [''], + ) + 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(), ['']) + a5.authors.set([user_2.username]) + self.assertQuerysetEqual(a5.authors.all(), ['']) + 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')