我使用的是django 2.0.8和Python 3.5。我编写了一个基类,它将行为封装在基类中。
保存对象时,应该打印一次消息。然而,当我运行应该保存对象的代码时,我得到消息“fireofmessage”打印了两次-为什么?
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
True foo 1 <QuerySet []>
Save Called!
Fire of like saved signal
Fire of like saved signal
当对象在数据库中只保存一次时,为什么要打印两次消息?