Sim*_*mon 2 django django-models django-testing django-tests
在我的网络应用程序中,我有地点和各自的开放时间。OpeningHours 模型如下所示:
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])
Run Code Online (Sandbox Code Playgroud)
我正在尝试测试一个模型,类似于我在应用程序中成功测试其他模型的方式:
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)
Run Code Online (Sandbox Code Playgroud)
,但是在运行测试时我收到此错误消息:
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'
Run Code Online (Sandbox Code Playgroud)
ordering我认为这可能与或元数据有关unique_together,但不确定如何解决这个问题......非常感谢任何正确方向的指针。
| 归档时间: |
|
| 查看次数: |
6531 次 |
| 最近记录: |