【问题标题】:Convention for checking the existence of a Django model?检查 Django 模型是否存在的约定?
【发布时间】:2010-02-06 01:06:32
【问题描述】:

在 Django 应用程序中检查模型是否存在的公认方法是什么?

我见过这种方法:

def profile_exists(user):
        try:
                UserProfile.objects.get(user = user)
                return True
        except:
                return False

是否有适合此目的的内置函数?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    不应使用裸excepts。而是模型的DoesNotExist 内部异常或django.core.exceptions.ObjectDoesNotExist should be caught。

    除此之外,无论是这个还是使用len(SomeModel.objects.filter(...))都是可以接受的。

    【讨论】:

      【解决方案2】:

      作为附加说明,您可以使用以下方法制作通用功能:

      def object_exists(model, **kwargs):
             try:
                   model.objects.get(**kwargs)
                   return True
             except model.DoesNotExist:
                   return False
      

      然后简单地调用:

      profile_exists = object_exists(UserProfile, user=user)
      

      【讨论】:

        【解决方案3】:

        那是适合直到赤裸裸的except。你总是得到比你讨价还价的更多!

        正如Ignacio Vazquez-Abrams 所提到的,应该利用模型内置的DoesNotExist 异常:

        def profile_exists(user):
                try:
                        UserProfile.objects.get(user = user)
                        return True
                except UserProfile.DoesNotExist:
                        return False
        

        快!

        【讨论】:

          【解决方案4】:

          总是有get_object_or_404,顾名思义,要么返回对象,要么引发HttpNotFound错误:

          from django.shortcuts import get_object_or_404
          instance = get_object_or_404(SomeModel, filter_args=whatever)
          

          【讨论】:

            猜你喜欢
            • 2021-01-05
            • 2016-11-30
            • 2017-12-21
            • 1970-01-01
            • 2019-09-01
            • 2011-09-07
            • 2021-07-13
            • 2021-02-26
            • 1970-01-01
            相关资源
            最近更新 更多