删除后存在django相关字段

时间:2017-12-21 18:52:33

标签: python django

我是订单模型和其他与之相关的模型。用户可以删除任何这些项目,如果删除后订单为空,我必须执行检查,如果为真,则设置为活动False。一些基本代码来说明它

class Order(models.Model):
    paid = models.BooleanField(default=False)
    active = models.BooleanField(default=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

    def empty_order():
         """
         I must implement it
         """

class HomeOrder(models.Model):
    ...
    order = models.OneToOneField(Order, related_name='primary_home')

class TourOrder(models.Model):
    ...
    order = models.ForeignKey(Order, related_name='tours')

我有一个post_delete信号与每个与Order相关的模型相关联:

post_delete.connect(delete_order_if_empty, sender=HomeOrder)
post_delete.connect(delete_order_if_empty, sender=TourOrder)

def delete_order_if_empty(sender, instance, **kwargs):
    if instance.order.empty_order():
        instance.order.active = False
        instance.order.save()

订单可以有一个Home,所以如果Home存在,我可以执行 order.primary_home ,如果Home不存在,它将引发AttributeError,因为它是OneToOne关系。

订单可以有多个Tours,所以在 empty_order 方法中,我想做一些检查,如下所示。

def empty_order():
    home = hasattr(self, 'primary_home')  # Avoid AttributeError exception
    tours = self.tours.exists()
    this_order_has_something = primary_home or tours
    return not this_order_has_something

现在,当我删除HomeOrder时,信号被引发但是empty_method从未意识到此HomeOrder不再存在。例如:

>>>o=Order.objects.create(...)
>>>o.primary_home # raise AttributeError
>>>h=HomeOrder.objetcs.create(order=o, ...)
>>>o.primary_home  # <HomeOrder: home-xx>
>>>h.delete()
>>>o.primary_home # still <HomeOrder: home-xx> Why?
>>>o.refresh_from_db()   
>>>o.primary_home # again <HomeOrder: home-xx>

0 个答案:

没有答案