Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define ManyToManyField in Django for tests

To test my serializers in django rest framework I use Model Name.objects.create method to create fields. But I can’t create ManyToManyField.

Guess, firstly I need to create objects for first model and for second model otherwise ManyToManyField bound can’t be created. But still can’t define ManyToManyField for test with create method.

Please help me to realize how it should work correctly. I’ve red django documentation, but haven’t got how to solve my issue.
Here is my code example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

models.py

class Book(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=7, decimal_places=2)
    author_name = models.CharField(max_length=200)
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='my_books')
    readers = models.ManyToManyField(User, through='UserBookRelation', related_name='books')

test.py

class BookSerializerTestCase(TestCase):

    def setUp(self):
        self.user = User.objects.create(username='test_username')
        self.book_1 = Book.objects.create(name='Test book 1', price=750, author_name='Author 1', owner=self.user)
        self.book_2 = Book.objects.create(name='Test book 2', price=650, author_name='Author 1', owner=self.user)

    def test_readers(self):
        users = [self.user]
        reader = self.book_1.readers.set(users)
        print(f'Readers: {reader}')

readers is None, how to define self.user?

Thank you in advance.

>Solution :

I think the command is correct. You can define ManyToMany using set and modify using add, remove.
You can also use just ids of them like the following.

self.book_1.readers.set([self.user.id])
self.book_1.readers.add(1)
self.book_1.readers.remove(1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading