result of filter query returning empty because of def __unicode__(self)

17 views
Skip to first unread message

Mike08

unread,
Jan 27, 2017, 12:32:14 AM1/27/17
to Django users

Does adding a def __unicode__(self): method into a model affect the queries being returned ?


I am currently experiencing a situation in which the presence of def __unicode__(self): in the model is interfering with the results being returned. 


These two are my models

   class modelLabTestName(models.Model):
        test_category = models.ForeignKey(modelLabCategory)
        test_name = models.CharField(max_length=128, unique=True , default="None")
        def __unicode__(self):  
            return self.test_name   #---------------------->--- Line A----  
            #return "Test Name : " + self.test_name ------->--- Line B----

class modelNormalLabTest(models.Model):
    test_name = models.ForeignKey(modelLabTestName,default=None)
    field_name = models.CharField(max_length=128)
    field_value = models.CharField(max_length=128)


Now notice in the above there are two lines A and B. Currently Line B is commented and this query works and I get back an object

lab_entries= modelNormalLabTest.objects.filter(test_name__test_name="ABC")


However if I replace

return self.test_name 

in the model modelLabTestName with this instead (Line B)

return "Test Name : " + self.test_name

The query fails (i.e - No object is returned)


My question is why is this happening and if there is any way for me to fix this issue. I already checked the value of the test_name property with the following statement and it is returning the correct value

t = modelLabTestName.objects.all()[0].test_name #t = "ABC"

then why is

lab_entries= modelNormalLabTest.objects.filter(test_name__test_name="ABC")

or even this

 modelLabTestName.objects.get(test_name="ABC");

returning nothing ? when the model modelLabTestname has the following method in it

def __unicode__(self):  
      return "Test Name : " + self.test_name 

Any suggestions would be appreciated. I am using Django (1.10.5)


Reply all
Reply to author
Forward
0 new messages