Peyman Salehi
Peyman Salehi

Reputation: 48

Write test for a Django model with many-to-many relation

I want to write a test for Django model with many-to-many relation but I got this error:

ValueError: "< Tour: tour >" needs to have a value for field "id" before this many-to-many relationship can be used.

My test:

class ModelTestCase(TestCase):
    def setUp(self):
        self.mock_file = mock.MagicMock(File)
        self.mock_file.name = 'MockFile'
        self.before_count = Tour.objects.count()
        self.tour_agency = TourAgency.objects.create(
            name='agency',
            username='agency')
        self.tour_category = TourCategory.objects.create(name='category')
        self.tour_equipment = TourEquipment.objects.create(name='equipment')
        self.tour_leader = TourLeader.objects.create(
            name='leader',
            email='[email protected]',
            username='leader',
            bio='sample text',)
        self.tour_tag = TourTag.objects.create(name='tag')

    def test_model_can_create_tour(self):
        self.tour = Tour.objects.create(
            name='tour',
            description='description',
            summary='summary',
            agency=self.tour_agency,
            equipment=self.tour_equipment,
            category=self.tour_category,
            tags=self.tour_tag,
            activity_type='activity type',
            date=datetime.now,
            photo=self.mock_file)
        self.tour.save()
        self.tour.save_m2m()
        count = Tour.objects.count()
        self.assertNotEqual(self.before_count, count)

I'll try to save objects with .save() but it doesn't work.

Upvotes: 2

Views: 6121

Answers (2)

atufa shireen
atufa shireen

Reputation: 407

To add Tags (m2m field) to the model, first save the model and then add tags to the model

self.tour.tags.add([tag names])

Upvotes: 0

Jostcrow
Jostcrow

Reputation: 369

You first need to save the tour model before adding the many-to-many relations. Looking at the code I think the many-to-many is the field 'tags'

def test_model_can_create_tour(self):
    self.tour = Tour.objects.create(
        name='tour',
        description='description',
        summary='summary',
        agency=self.tour_agency,
        equipment=self.tour_equipment,
        category=self.tour_category,
        activity_type='activity type',
        date=datetime.now,
        photo=self.mock_file)

    # Adding the tour later.
    self.tour.tags.add(self.tour_tag)
    count = Tour.objects.count()
    self.assertNotEqual(self.before_count, count)

This should pass the tests.

Upvotes: 3

Related Questions