Search code examples
djangodjango-modelsdjango-testingdjango-tests

Django Test: type object has no attribute 'objects'


In my web application, I have locations and respective opening hours. The OpeningHours model looks as follows:

class OpeningHours(models.Model):
    location = models.ForeignKey(
        Location, related_name='hours', on_delete=models.CASCADE)
    weekday = models.PositiveSmallIntegerField(choices=WEEKDAYS, unique=True)
    from_hour = models.PositiveSmallIntegerField(choices=HOUR_OF_DAY_12)
    to_hour = models.PositiveSmallIntegerField(choices=HOUR_OF_DAY_12)

    class Meta:
        ordering = ('weekday', 'from_hour')
        unique_together = ('weekday', 'from_hour', 'to_hour')

    def get_weekday_display(self):
        return WEEKDAYS[self.weekday][1]

    def get_hours_display(self):
        return '{} - {}'.format(HOUR_OF_DAY_12[self.from_hour][1], HOUR_OF_DAY_12[self.to_hour][1])

    def get_start_hour_display(self):
        return HOUR_OF_DAY_12[self.from_hour][1]

    def get_end_hour_display(self):
        return HOUR_OF_DAY_12[self.to_hour][1]

    def __str__(self):
        return '{}: {} - {}'.format(self.get_weekday_display(),
                                    HOUR_OF_DAY_12[self.from_hour][1], HOUR_OF_DAY_12[self.to_hour][1])

I'm trying to test a model similar to how I have successfully tested other models in my application:

class OpeningHours(TestCase):

    def create_opening_hours(self, weekday=1, from_hour=12, to_hour=15):
        self.location = create_location(self)
        return OpeningHours.objects.create(location=self.location, weekday=weekday, from_hour=from_hour, to_hour=to_hour)

    def test_opening_hours(self):
        oh = self.create_opening_hours()
        self.assertTrue(isinstance(oh, OpeningHours))
        self.assertTrue(0 <= oh.from_hour <= 23)
        self.assertTrue(0 <= oh.to_hour <= 23)
        self.assertTrue(1 <= oh.weekday <= 7)

, but when running the test I get this error message:

Traceback (most recent call last):
  File "<app_path>/tests.py", line 137, in test_opening_hours
    oh = self.create_opening_hours()
  File "<app_path>/tests.py", line 134, in create_opening_hours
    return OpeningHours.objects.create(location=self.location, weekday=weekday, from_hour=from_hour, to_hour=to_hour)
AttributeError: type object 'OpeningHours' has no attribute 'objects'

I assume this could have to do with the ordering or unique_together metadata, but not sure how to solve this... any pointers in the right direction very much appreciated.


Solution

  • You have given OpeningHours name to your test class as well as to the model class. So change the name of the test class to anything other than OpeningHours will solve the mentioned issue.