Joh*_*ght 79 python django-models one-to-one
我有两个这样的模型:
class Type1Profile(models.Model):
user = models.OneToOneField(User, unique=True)
...
class Type2Profile(models.Model):
user = models.OneToOneField(User, unique=True)
...
Run Code Online (Sandbox Code Playgroud)
如果用户具有Type1或Type2配置文件,我需要做一些事情:
if request.user.type1profile != None:
# do something
elif request.user.type2profile != None:
# do something else
else:
# do something else
Run Code Online (Sandbox Code Playgroud)
但是,对于没有type1或type2配置文件的用户,执行这样的代码会产生以下错误:
Type1Profile matching query does not exist.
Run Code Online (Sandbox Code Playgroud)
如何查看用户的个人资料类型?
谢谢
joc*_*tee 83
要检查(OneToOne)关系是否存在,可以使用以下hasattr函数:
if hasattr(request.user, 'type1profile'):
# do something
elif hasattr(request.user, 'type2profile'):
# do something else
else:
# do something else
Run Code Online (Sandbox Code Playgroud)
Jos*_*low 45
这是可能的,看看是否可空的一个一对一的关系是空特定模型简单地通过在模型中测试相应的领域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()
Run Code Online (Sandbox Code Playgroud)
...看看是否Restaurant有a 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!
Run Code Online (Sandbox Code Playgroud)
要查看a Place是否有a 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.
Run Code Online (Sandbox Code Playgroud)
在这种情况下,奥卡姆剃刀盛行,并作出一个关于是否确定最好的方法Place有Restautrant将是一个标准try/ except描述构建这里.
>>> try:
>>> restaurant = p2.restaurant
>>> except Restaurant.DoesNotExist:
>>> print "Place has no restaurant!"
>>> else:
>>> # Do something with p2's restaurant here.
Run Code Online (Sandbox Code Playgroud)
虽然joctee建议hasattr在实践中使用作品,但它实际上只是偶然起作用,因为它会hasattr抑制所有异常(包括DoesNotExist)而不是AttributeErrors,就像它应该的那样.正如Piet Delport指出的那样,这个行为实际上在Python 3.2中通过以下票证得到了纠正:http://bugs.python.org/issue9666.此外 - 并且冒着听起来很自负的风险 - 我相信上面的try/ except构造更能代表Django的工作方式,而使用hasattr可以为新手解决问题,这可能会造成FUD并传播坏习惯.
Don*_*kby 14
我喜欢joctee的回答,因为它很简单.
if hasattr(request.user, 'type1profile'):
# do something
elif hasattr(request.user, 'type2profile'):
# do something else
else:
# do something else
Run Code Online (Sandbox Code Playgroud)
其他评论者担心它可能不适用于某些版本的Python或Django,但Django文档将此技术显示为以下选项之一:
您还可以使用hasattr来避免异常捕获的需要:
>>> hasattr(p2, 'restaurant')
False
Run Code Online (Sandbox Code Playgroud)
当然,文档还显示了异常捕获技术:
p2没有相关的餐厅:
>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
>>> p2.restaurant
>>> except ObjectDoesNotExist:
>>> print("There is no restaurant here.")
There is no restaurant here.
Run Code Online (Sandbox Code Playgroud)
我同意约书亚的看法,即抓住这个例外会让事情变得更加清晰,但这对我来说似乎更加混乱.也许这是一个合理的妥协?
>>> print(Restaurant.objects.filter(place=p2).first())
None
Run Code Online (Sandbox Code Playgroud)
这只是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()
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)
然后,像这样使用!
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!
Run Code Online (Sandbox Code Playgroud)
我想你可以使用它作为通用函数来获取任何反向的OneToOne实例,给定一个原始类(这里:你的配置文件类)和一个相关的实例(这里:request.user).
| 归档时间: |
|
| 查看次数: |
26009 次 |
| 最近记录: |