检查OneToOneField在Django中是否为None


86

我有两个这样的模型:

class Type1Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    ...


class Type2Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    ...

如果用户具有Type1或Type2配置文件,我需要做一些事情:

if request.user.type1profile != None:
    # do something
elif request.user.type2profile != None:
    # do something else
else:
    # do something else

但是,对于没有类型1或类型2概要文件的用户,执行这样的代码会产生以下错误:

Type1Profile matching query does not exist.

如何检查用户拥有的个人资料类型?

谢谢

Answers:


93

要检查(OneToOne)关系是否存在,可以使用以下hasattr函数:

if hasattr(request.user, 'type1profile'):
    # do something
elif hasattr(request.user, 'type2profile'):
    # do something else
else:
    # do something else

4
感谢您的解决方案。不幸的是,这并不总是有效。如果您想select_related()现在或将来使用它-甚至可能要确保您还处理其他地方可能发生的其他魔术-您必须按以下方式扩展测试:if hasattr(object, 'onetoonerevrelattr') and object.onetoonerevrelattr != None
类堆栈器

7
请注意,在Python <3.2中,hasattr它将吞噬数据库查找期间发生的所有异常,而不仅仅是DoesNotExist。这可能是坏的,而不是您想要的。
Pi Delport

不适用于python 2.7。即使OneToOne不存在,它也会返回django.db.models.fields.related.RelatedManager对象。
alexpirine

@alartur您使用的是哪个Django版本?
joctee

Django 1.5。但是我通过以完全不同的方式实现我想做的事情解决了我的特殊问题。
alexpirine 2013年

48

这是可能的,看看是否可空的一个一对一的关系是空特定模型简单地通过在模型中测试相应的领域None湖,但只有当你的模型,其中一个一对一的关系起源测试。例如,给定这两个类……

class Place(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

class Restaurant(models.Model):  # The class where the one-to-one originates
    place = models.OneToOneField(Place, blank=True, null=True)
    serves_hot_dogs = models.BooleanField()
    serves_pizza = models.BooleanField()

…查看aRestaurant是否具有Place,我们可以使用以下代码:

>>> r = Restaurant(serves_hot_dogs=True, serves_pizza=False)
>>> r.save()
>>> if r.place is None:
>>>    print "Restaurant has no place!"
Restaurant has no place!

要查看aPlace是否具有Restaurant,重要的是要理解,如果没有相应的餐厅,则restaurant在实例上引用该属性Place会引发Restaurant.DoesNotExist异常。发生这种情况是因为Django内部使用进行查找QuerySet.get()。例如:

>>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
>>> p2.save()
>>> p2.restaurant
Traceback (most recent call last):
    ...
DoesNotExist: Restaurant matching query does not exist.

在这种情况下,Occam的剃须刀占了上风,确定此处是否Place具有a的最佳方法是此处所述Restautrant的标准try/except构造。

>>> try:
>>>     restaurant = p2.restaurant
>>> except Restaurant.DoesNotExist:
>>>     print "Place has no restaurant!"
>>> else:
>>>     # Do something with p2's restaurant here.

尽管joctee的建议是hasattr在实践中使用工程,但实际上它是偶然的,因为它hasattr抑制了所有例外(包括DoesNotExist),而不是AttributeErrors,就像应该那样。正如Pi Delport所指出的,以下行为实际上已在Python 3.2中纠正了此行为:http : //bugs.python.org/issue9666。此外,我相信上面的try/except构造更能代表Django的工作方式,并且冒着听起来固执己见的风险,尽管使用hasattr可以使新手感到困惑,这可能会造成FUD并传播不良习惯。

编辑 唐·柯比的合理妥协对我来说也很合理。


19

我喜欢joctee的回答,因为它很简单。

if hasattr(request.user, 'type1profile'):
    # do something
elif hasattr(request.user, 'type2profile'):
    # do something else
else:
    # do something else

其他评论者担心它可能不适用于某些版本的Python或Django,但Django文档将此技术显示为一种选择:

您还可以使用hasattr避免捕获异常:

>>> hasattr(p2, 'restaurant')
False

当然,文档还显示了异常捕获技术:

p2没有关联的餐厅:

>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
>>>     p2.restaurant
>>> except ObjectDoesNotExist:
>>>     print("There is no restaurant here.")
There is no restaurant here.

我同意约书亚(Joshua)的观点,捕获异常可以使发生的事情更加清晰,但对我来说似乎更麻烦。也许这是一个合理的妥协?

>>> print(Restaurant.objects.filter(place=p2).first())
None

这只是Restaurant按位置查询对象。None如果该地方没有餐厅,它将返回。

这是供您使用这些选项的可执行代码段。如果您安装了Python,Django和SQLite3,则应运行它。我使用Python 2.7,Python 3.4,Django 1.9.2和SQLite3 3.8.2对其进行了测试。

# Tested with Django 1.9.2
import sys

import django
from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import connections, models, DEFAULT_DB_ALIAS
from django.db.models.base import ModelBase

NAME = 'udjango'


def main():
    setup()

    class Place(models.Model):
        name = models.CharField(max_length=50)
        address = models.CharField(max_length=80)

        def __str__(self):              # __unicode__ on Python 2
            return "%s the place" % self.name

    class Restaurant(models.Model):
        place = models.OneToOneField(Place, primary_key=True)
        serves_hot_dogs = models.BooleanField(default=False)
        serves_pizza = models.BooleanField(default=False)

        def __str__(self):              # __unicode__ on Python 2
            return "%s the restaurant" % self.place.name

    class Waiter(models.Model):
        restaurant = models.ForeignKey(Restaurant)
        name = models.CharField(max_length=50)

        def __str__(self):              # __unicode__ on Python 2
            return "%s the waiter at %s" % (self.name, self.restaurant)

    syncdb(Place)
    syncdb(Restaurant)
    syncdb(Waiter)

    p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
    p1.save()
    p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
    p2.save()
    r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
    r.save()

    print(r.place)
    print(p1.restaurant)

    # Option 1: try/except
    try:
        print(p2.restaurant)
    except ObjectDoesNotExist:
        print("There is no restaurant here.")

    # Option 2: getattr and hasattr
    print(getattr(p2, 'restaurant', 'There is no restaurant attribute.'))
    if hasattr(p2, 'restaurant'):
        print('Restaurant found by hasattr().')
    else:
        print('Restaurant not found by hasattr().')

    # Option 3: a query
    print(Restaurant.objects.filter(place=p2).first())


def setup():
    DB_FILE = NAME + '.db'
    with open(DB_FILE, 'w'):
        pass  # wipe the database
    settings.configure(
        DEBUG=True,
        DATABASES={
            DEFAULT_DB_ALIAS: {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': DB_FILE}},
        LOGGING={'version': 1,
                 'disable_existing_loggers': False,
                 'formatters': {
                    'debug': {
                        'format': '%(asctime)s[%(levelname)s]'
                                  '%(name)s.%(funcName)s(): %(message)s',
                        'datefmt': '%Y-%m-%d %H:%M:%S'}},
                 'handlers': {
                    'console': {
                        'level': 'DEBUG',
                        'class': 'logging.StreamHandler',
                        'formatter': 'debug'}},
                 'root': {
                    'handlers': ['console'],
                    'level': 'WARN'},
                 'loggers': {
                    "django.db": {"level": "WARN"}}})
    app_config = AppConfig(NAME, sys.modules['__main__'])
    apps.populate([app_config])
    django.setup()
    original_new_func = ModelBase.__new__

    @staticmethod
    def patched_new(cls, name, bases, attrs):
        if 'Meta' not in attrs:
            class Meta:
                app_label = NAME
            attrs['Meta'] = Meta
        return original_new_func(cls, name, bases, attrs)
    ModelBase.__new__ = patched_new


def syncdb(model):
    """ Standard syncdb expects models to be in reliable locations.

    Based on https://github.com/django/django/blob/1.9.3
    /django/core/management/commands/migrate.py#L285
    """
    connection = connections[DEFAULT_DB_ALIAS]
    with connection.schema_editor() as editor:
        editor.create_model(model)

main()

10

如何使用try / except块?

def get_profile_or_none(user, profile_cls):

    try:
        profile = getattr(user, profile_cls.__name__.lower())
    except profile_cls.DoesNotExist:
        profile = None

    return profile

然后,像这样使用!

u = request.user
if get_profile_or_none(u, Type1Profile) is not None:
    # do something
elif get_profile_or_none(u, Type2Profile) is not None:
    # do something else
else:
    # d'oh!

我想您可以将其用作泛型函数,以获取任何反向的OneToOne实例,给定一个原始类(在这里:您的个人资料类)和一个相关实例(在这里:request.user)。


3

使用select_related

>>> user = User.objects.select_related('type1profile').get(pk=111)
>>> user.type1profile
None

2
我知道它的工作原理是这样的,但是select_related的这种行为是否实际记录在案?
科斯(Kos)

3
我刚刚在Django 1.9.2中尝试过,它引发了RelatedObjectDoesNotExist
Don Kirkby

1

如果你有模型

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True)

您只需要为任何用户知道UserProfile存在/不存在- 从数据库的角度来看,最有效的方式是使用query

存在查询将仅返回布尔值,而不是反向访问属性,例如hasattr(request.user, 'type1profile')-将生成get查询并返回完整的对象表示形式

为此,您需要向用户模型添加属性

class User(AbstractBaseUser)

@property
def has_profile():
    return UserProfile.objects.filter(user=self.pk).exists()

0

我正在使用has_attr的组合,并且为None:

class DriverLocation(models.Model):
    driver = models.OneToOneField(Driver, related_name='location', on_delete=models.CASCADE)

class Driver(models.Model):
    pass

    @property
    def has_location(self):
        return not hasattr(self, "location") or self.location is None

0

一种聪明的方法是添加自定义字段OneToOneOrNoneField使用它[适用于Django> = 1.9]

from django.db.models.fields.related_descriptors import ReverseOneToOneDescriptor
from django.core.exceptions import ObjectDoesNotExist
from django.db import models


class SingleRelatedObjectDescriptorReturnsNone(ReverseOneToOneDescriptor):
    def __get__(self, *args, **kwargs):
        try:
            return super().__get__(*args, **kwargs)
        except ObjectDoesNotExist:
            return None


class OneToOneOrNoneField(models.OneToOneField):
    """A OneToOneField that returns None if the related object doesn't exist"""
    related_accessor_class = SingleRelatedObjectDescriptorReturnsNone

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('null', True)
        kwargs.setdefault('blank', True)
        super().__init__(*args, **kwargs)

实作

class Restaurant(models.Model):  # The class where the one-to-one originates
    place = OneToOneOrNoneField(Place)
    serves_hot_dogs = models.BooleanField()
    serves_pizza = models.BooleanField()

用法

r = Restaurant(serves_hot_dogs=True, serves_pizza=False)
r.place  # will return None

对于Django 1.8,您需要使用 SingleRelatedObjectDescriptor而不是ReverseOneToOneDescriptor这样 from django.db.models.fields.related import SingleRelatedObjectDescriptor
pymen
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.