假设我们有一个 MarkPost 模型。此模型与发布模型具有ForeinKey关系。
class Post(models.Model):
TITLE = (
('1', 'USA'),
('2', 'Europe'), )
title = models.CharField(max_length=1, choices=TITLE)
class MarkPost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE,
related_name="marked")
示例:
foo_post = Post.objects.create(title="1")
marked_post1 = MarkPost.objects.create(user="Foo", post=foo_post)
我试图写一些信号通知,如果另一个Post实例使用值 marked_post1.post.title 制作,请通过 marked_post1 通知相关用户.I为此目的发挥了信号功能。
signals.py
def created_post(sender, instance, created, **kwargs):
marked = MarkPost.objects.get(pk=1)
marked_title = marked.post.title
if created and instance.title == marked_title :
#logic of my code
print(" new post made ")
post_save.connect(created_post, sender=Post)
这适用于一个实例但是如何以标记Post的每个用户的一般方式执行此操作?
答案 0 :(得分:1)
假设您在MarkPost
的id计算后面有一个定义的逻辑,
def logic_to_find_markpost_id(req_data):
# do stuff to find MarkPost's id
return markpost_id
def created_post(sender, instance, created, **kwargs):
markpost_id = logic_to_find_markpost_id(req_data)
marked = MarkPost.objects.get(pk=markpost_id)
marked_title = marked.post.title
if created and instance.title == marked_title:
# logic of your code
print(" new post made ")
post_save.connect(created_post, sender=Post)