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.
question from:
https://stackoverflow.com/questions/66056433/django-test-type-object-has-no-attribute-objects 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…