datetime的小坑

时间:2024-10-25 12:36:38

在做悦运动这个项目时,在创建约运动关系表时,运动开始时间,注意(导入datetime包时,我导入的是class datetime(__datetime.date)这个类,可以调用这个类中的方法,调用当前时间直接可以调用datetime.now()

 from datetime import datetime
......
class Schedule(models.Model):
'''
发起约运动
'''
Status = ((1, '已完成'), (2, '待人加入'), (3, '已取消'))
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='发起人')
join_type = models.BooleanField(verbose_name='是否发起人')
now_people = models.IntegerField(verbose_name='已有人数', null=True, blank=True)
school = models.ForeignKey(Schools, on_delete=models.CASCADE, verbose_name='学校', default='')
sport = models.ForeignKey(Sports, on_delete=models.CASCADE, verbose_name='运动项目')
address = models.CharField(verbose_name='约定地点', max_length=100)
sport_time = models.DateTimeField(verbose_name='约定运动开始时间')
sport_end_time = models.DateTimeField(verbose_name='约定运动结束时间', default='')
people_nums = models.IntegerField(verbose_name='人数')
add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
status = models.IntegerField(choices=Status, verbose_name='状态') class Meta:
verbose_name = '发起约运动'
verbose_name_plural = verbose_name def __str__(self):
return self.sport.sport_name + '-' + str(self.sport_time) class JoinSchedule(models.Model):
'''
加入的运动
'''
schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE, verbose_name='加入的运动')
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='用户')
add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间') class Meta:
verbose_name = '加入运动'
verbose_name_plural = verbose_name def __str__(self):
return str(self.schedule_id) + '--' + str(self.user_id)

而在序列化该表时,导入的是datetime:class datetime,包含了datetime这个模块所有方法,获得当前时间可以datetime.datetime.now(),如第十五行

 import datetime
class MyJoinScheduleSerializer(serializers.ModelSerializer):
'''
加入约运动序列化
'''
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S') def create(self, validated_data):
user = self.context['request'].user
schedule = validated_data['schedule']
if Schedule.objects.filter(user=schedule.user, id=schedule.id).first().user == user:
raise serializers.ValidationError('您是该运动的发起人,已默认加入')
double_status = False
schedules = JoinSchedule.objects.filter(user=user,schedule__sport_time__gt=datetime.datetime.now())
if schedules:
for s in schedules:
if s.schedule.sport_time > schedule.sport_end_time or schedule.sport_time >= s.schedule.sport_end_time:
pass
else:
double_status = True
break
if double_status:
raise serializers.ValidationError({"time_error":"与你已有的预约运动时间冲突"})
else:
existed = JoinSchedule.objects.create(**validated_data)
return existed class Meta:
model = JoinSchedule
fields = '__all__'
validators = [
UniqueTogetherValidator(
queryset=JoinSchedule.objects.all(),
fields=('user', 'schedule'),
message='已经加入'
)
]

运行测试时会报错;type object 'datetime.datetime' has no attribute 'datetime'(对象'datetime.datetime'类型没有属性'datetime'),原因:

from datetime import datetime 已经相当于把命名空间引入到datetime.datetime一层,而在序列化时,又是import datetime,调用datetime.datetime.noe()会让编译器在datetime.datetime空间下去找datetime类。

但是datetime类是应该在datetime空间下的,所以会报错,主要是由于两个datetime不是一个等级的。