Django check if a related object exists error: RelatedObjectDoesNotExist

前端 未结 2 1854
陌清茗
陌清茗 2021-01-30 12:10

I have a method has_related_object in my model that needs to check if a related object exists

class Business(base):
      name =  models.CharField(ma         


        
相关标签:
2条回答
  • 2021-01-30 12:47

    This is because the ORM has to go to the database to check to see if customer exists. Since it doesn't exist, it raises an exception.

    You'll have to change your method to the following:

    def has_related_object(self):
        has_customer = False
        try:
            has_customer = (self.customers is not None)
        except Customer.DoesNotExist:
            pass
        return has_customer and (self.car is not None)
    

    I don't know the situation with self.car so I'll leave it to you to adjust it if it needs it.

    Side note: If you were doing this on a Model that has the ForeignKeyField or OneToOneField on it, you would be able to do the following as a shortcut to avoid the database query.

    def has_business(self):
        return self.business_id is not None
    
    0 讨论(0)
  • 2021-01-30 13:06

    Use hasattr(self, 'customers') to avoid the exception check as recommended in Django docs:

    def has_related_object(self):
        return hasattr(self, 'customers') and self.car is not None
    
    0 讨论(0)
提交回复
热议问题