I'm trying to test some part of a Django project. The test is:
class SearchTest(TestCase):
def test_object_added(self):
SomeSingleton().add_one_object_to_model()
tmp = SomeModel.objects.latest('id')
self.assertEqual(tmp.some_field,SOME_VALUE)
Here I'm calling some function to add somehow an object to a model. The creation model is related to some Celery task execution. The purpose of the test is to check a value of the field of the added model. So when an object is added to the model it becomes the latest by id.
I got this when I ran ./manage.py test some_app:
DoesNotExist: CeleryTask matching query does not exist.
I found this question here and tried to do the same thing. I changed 'id' in tmp = SomeModel.objects.latest('id') to all the possible variants: u'id', u'"id"' and even u"id" and u"'id'". I was still getting the same issue to the variants with single quotation sign type. But I got
FieldError: Invalid order_by arguments: [u'-"id"']
to the variants with both quotation sign types. It's alright, do we have any other ways to get the latest object of a model? I haven't found one that works. I tried to declare get_latest_by = "id" at class Meta but I got the same issue about query that doesn't exist.
I tried some Python ways (I still work with kind of a list, right?) like tmp = SomeModel.objects.all()[-1], SomeModel.objects.all()[len(SomeModel.objects.all())-1] and the issue was
AssertionError: Negative indexing is not supported.
Then I tried SomeModel.objects.all().reverse()[0] but was answered immediately:
IndexError: list index out of range
I'm frankly baffled. All of these ways work good when typed at ./manage.py shell so I can get the latest model but for some reason it doesn't happen when using ./manage.py test some_app. What is the right way to cope with it?
idshouldn't be unicode, it should be an int so that question wouldn't apply to you. From the error message, it looks like the problem is that django can't find your celery task when running the tests. ThisSomeSingleton().add_one_object_to_model()is most likely the cause of your issues notSomeModel.objects.latest('id')