我正在使用Django 2.0.8和Python 3.5。我写了一个基类,将行为封装在基类中。
保存对象后,应该立即打印一条消息。但是,当我运行应该保存对象的代码时,得到的消息“消息之火”打印了两次-为什么?
这是我的代码:
Restart-Service WinRM
class Likeable(models.Model):
likes = GenericRelation(Like)
def action_is_permissible(self, actionable_object, actor):
ct = ContentType.objects.get_for_model(actionable_object)
object_id = actionable_object.id
found_objects = Like.objects.filter(content_type=ct, object_id=object_id, liker=actor)
return ((len(found_objects) == 0), ct, object_id, found_objects)
def add_like(self, actionable_object, actor):
can_add, ct, object_id, found_objects = self.action_is_permissible(actionable_object, actor)
print(can_add, ct, object_id, found_objects)
if can_add:
print('Save Called!')
# Create like object and save it
like = self.likes.create(content_type=ct, object_id=object_id, liker=actor)
like.save()
else:
# do nothing
print('Nothing doing')
return
class Meta:
abstract = True
class Foo(Likeable):
name = models.CharField(max_length=255,default='')
objects = models.Manager()
foo = Foo.objects.get(id=1)
p = User.objects.get(id=1)
foo.add_like(foo, p) # <- nasty API calling convention, but I digress
为什么将消息打印两次-当对象仅在数据库中保存一次时?
答案 0 :(得分:2)
这里:
like = self.likes.create(content_type=ct, object_id=object_id, liker=actor)
like.save()
QuerySet.create()
实际上确实在实例上调用save()
-否则该方法将只是模型的初始化程序的无用重复-因此您确实有两次调用。