python - 用 Django 信号通知用户 _ Django

标签 python django

假设我们有一个模型MarkPost。此模型与 Post 模型具有 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 实例的值是 ma​​rked_post1.post.title ,则通知 ma​​rked_post1 中的相关用户。我做了一个为此目的的信号函数。

信号.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)

这将适用于一个实例,但如何以通用方式为标记帖子的每个用户执行此操作?

最佳答案

假设您在 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)

关于python - 用 Django 信号通知用户 _ Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404705/

相关文章:

django-allauth:如何为我的域添加站点?

python - 将 xml 转换为字典时处理错误

python - Django 仅在一个特定字段更改时发送邮件

python - Django 两个模型字段,相同的数据库列

python - 如何在 aws cdk 中添加往返端口?

python - 使用 Python C API 将 Python 中的函数移植到 C 时遇到问题

Python Windows 服务 pyinstaller 可执行文件错误 1053

python - 将一对变量分配给 Python 中两个变量的最小值/最大值

python - 基于组分配的 Pandas 数据帧到稀疏矩阵(如果在组中则为 1,如果不在组中则为 0)

python - 如何在 Django 中对日期和时间执行聚合?