Search code examples
pythonsqldjangotddmodels

Django Models .get fails but .filter and .all works - object exists in database


Racking my brain on this one. The model seems true, theoretically all of the commented permutations should work--- but the only things that can successfully retrieve the user is .filter and .all; .get doesnt work; I can deal with using either .filter or .all ---- but why isn't get working?

I'll reiterate that a direct SQL query works 100% in this case. All imports are in place and things are functioning great at a low level -- again, Filter works, All works, but get fails for some reason.

class UserModelTest(TestCase):
def test_getUserByUsername(self):
    sanity = True
    try:
        #u = User.objects.filter(username='wadewilliams')
        u = User.objects.get(username='wadewilliams')
        #u = User.objects.get(pk=15773)
        #u = User.objects.all()
    print u
    except User.DoesNotExist:
        sanity = False

    self.assertEqual(sanity, True)

... That test fails unless I uncomment either filter or all... both gets, no go.

And the model...

class User(models.Model):
    userid = models.IntegerField(primary_key=True, db_column='userID')
    username = models.CharField(max_length=135)
    realname = models.CharField(max_length=150, db_column='name')
    email = models.CharField(max_length=765, blank=True)

class Meta:
    db_table = u'users'

def __unicode__(self):
    return self.username + ' (' + self.email + ')'

Solution

  • The test suite creates a mock database that is blank, so no users can be found even though the exist in the production/development database.

    From the docs: Finding data from your production database when running tests? If your code attempts to access the database when its modules are compiled, this will occur before the test database is set up, with potentially unexpected results. For example, if you have a database query in module-level code and a real database exists, production data could pollute your tests. It is a bad idea to have such import-time database queries in your code anyway - rewrite your code so that it doesn't do this.