Home > Mobile >  how do I write test cases for __str__ method for a model having two ManyToManyFields in Django Rest
how do I write test cases for __str__ method for a model having two ManyToManyFields in Django Rest

Time:05-12

Here are the three models where in the 3rd model we relate the above two models. #models.py

class CategoryDetail(models.Model):
    categoryCode = models.BigAutoField(
        primary_key=True)
    categoryName = models.CharField(max_length=100)
    categoryDescription = models.CharField(max_length=500)

    def __str__(self):
        return self.categoryName

class ProductDetail(models.Model):
    productCode = models.BigAutoField(primary_key=True)
    productName = models.CharField(max_length=100)
    manufacturer = models.CharField(max_length=100)

    def __str__(self):
        return self.productName

class ProductCategoryMapping(models.Model):
    productCategoryCode= models.BigAutoField(primary_key=True)
    productCode= models.ManyToManyField(ProductDetail, related_name='category')
    categoryCode = models.ManyToManyField(CategoryDetail)

    def __str__(self):
        return '%s: %s' % (self.productCategoryCode, self.categoryCode)

here is the test written which is having errors

def test_CategoryMapping_str(self):
        product1 = ProductDetail.objects.create(productName = 'AquaTouch')
        category1= CategoryDetail.objects.create(categoryName = 'Trimmer & Shaver')
        categoryMapped = ProductCategoryMapping.objects.create(productCategoryCode= '1', productCode= product1.productCode, categoryCode= category1.categoryCode)
        self.assertEqual(str(categoryMapped), '1:Trimmer & Shaver ')

The errorMessage says: "Direct assignment to the forward side of a many-to-many set is prohibited. Use productCode.set() instead"

CodePudding user response:

The issue is happening, as the error states, because you're trying to set the many-to-many fields directly within your .create (productCode=product1.productCode and categoryCode=category1.categoryCode).

You should be using .set() afterwards:

categoryMapped = ProductCategoryMapping.objects.create(productCategoryCode= '1')
categoryMapped.productCode.set([product1])
categoryMapped.categoryCode.set([category1])

Take a look at the docs as well.

  • Related