Testing a many to many relationship

Hi

so i have a django model which is a bit long, but the part we need is:

catalog/models.py


from django.db import models

class Genres(models.Model):
name = models.Charfield(max_length=200)

def str(self):
return self.name

class Book(models.Model):
“”“some data”“”
genres = models.ManyToManyField(Genre)


which seem to work fine on the admin site
BUT
i can’t seem to be able to test it

my test:


from django.test import TestCase
from .models import Books, Genres

class BookTest(TestCase):
def setUp(self):
“”“i also tried with setUpTestData classmethode”“”
self.genres =
Genres.objects.create(name=“drama”)

self.book = Book.objects.create(
   """some data"""
)
self.all_genres = Genres.objects.all()
self.book.genre.set(self.all_genres)
self.book.save()

and then i assert that


self.assertEqual(f"{self.book.genre}", “drama”)


my error:


Traceback (most recent call last):
File “C:\Users\313.Co\Desktop\django_project\catalog\tests.py”, line 65, in test_book_listing
self.assertEqual(f"{self.book.genres}", “drama”)
AssertionError: ‘catalog.Genres.None’ != ‘drama’

  • catalog.Genres.None
  • drama

Hi,

First, there are some inconsistencies in your code between “Genre” vs “Genres”, “genres” vs “genre”. I guess these are typo errors you made when copy-pasting your code in this post, as such code would lead to application completely failing before you can execute the test.

self.book.genre is a queryset, gence the representation you get. A correct test would be

self.assertListEqual([str(genre) for genre in self.book.genres.all()], ["drama"])
1 Like