django - 多对多关系查询在 post_save 信号上返回空查询集,但在 django shell 中不返回

标签 django django-models

我的模型中有一个功能,可以在成功保存时发送电子邮件。但我正在努力弄清楚为什么模型中信号函数的打印语句返回空查询集而不是在 shell 中。下面是我的代码。 模型代码

class Booking(models.Model):
    """Database table for users booking details"""
   //more code here
    items = models.ManyToManyField(BookingItems)
    //more code here
def send_confirmation_email(sender, instance, **kwargs):
    """Function to send email upon successfull booking creation"""
    name = instance.guest_name
    total = instance.final_total,
    email = instance.email
    order_number = instance.reservation_id
    bookingId = instance.id
    itemsData = instance.items.all()
    booking = Booking.objects.get(id=bookingId)
    bookingItems = booking.items.all()
    print(bookingItems)-----------------------------------> this returns empty queryset <QuerySet []>
    context = {"name": name, "items": itemsData, 'total': total,
               'order_number': order_number}
    message = render_to_string(
        "reservations/room_reservation_success.html", context)
    plain_message = strip_tags(message)
    subject = f"Your booking details for {instance.hotel.name}"
    mail.send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [
        email], html_message=message)


post_save.connect(send_confirmation_email, sender=Booking)

shell 代码

>>> book = Booking.objects.filter(id=61)
>>> print(book[0].items.all())
<QuerySet [<BookingItems: One bedroom>, <BookingItems: Two bedroom>]>
>>> 

这里可能是什么问题。当有明显相关的子项时,为什么返回空集?请协助

最佳答案

What could be the issue here. Why is it returning empty set when there's clearly related child items?

post_save 触发器运行时没有相关(子)项。因为如果您保存多对多关系,您首先保存对象,然后您保存与其他对象的关系。你以前不能这样做,因为那时它还没有主键。 post_save 在填充多对多字段之前被触发。

您可以在将元素添加到与 m2m_changed signal [Django-doc] 的多对多关系之后执行查询,而不是在保存 Booking 时触发。 :

def send_confirmation_email(sender, instance<b>, action</b>, **kwargs):
    if <b>action == 'post_add'</b>:
        # …
        pass


<b>m2m_changed</b>.connect(send_confirmation_email, <b>sender=Booking.items.through</b>)

也就是说,信号通常是 considered an anti-pattern [Django-doc] .特别是因为有很多 ORM 调用可以绕过信号。在 View 中实现它可能更容易,因此在保存整个对象后触发一个函数。

关于django - 多对多关系查询在 post_save 信号上返回空查询集,但在 django shell 中不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63538796/

相关文章:

python - Heroku 的 Django 项目无法使用 pip 安装依赖项

python - 如何在 Django Rest API 中从父模型中过滤子对象?

python - 如何在 django rest 框架中反转 ViewSet 自定义操作的 URL

Django:检查是否设置了外键属性

django - 比较两个对象[动态使用字段]

django - 检查条件时避免在 django 模板中进行额外的 SQL 调用

django - Django项目工作目录结构最佳实践

python - 你如何在 Django 聚合中动态分配别名?

django - 非空TextField的QuerySet

python - Django - 验证 m2m 关系