Django:访问抽象模型的子类
我有几个从一个基类继承的用户配置文件模型,如下所示:
class BaseProfile(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
...
class Meta:
abstract = True
class DoctorProfile(BaseProfile):
license_no = models.CharField(max_length=10)
...
class PharmacistProfile(BaseProfile):
pass
当我有一个用户实例时,我想获取他们的配置文件。
我不想一一检查用户是否有个人资料。像这样:
if user.doctorprofile_set.all().count() == 1:
return user.doctorprofile_set.all()[0]
elif user.pharmacistprofile_set.all().count() == 1:
return user.pharmacistprofile_set.all()[0]
...
对于每个配置文件是最好的方法,因为它不是 DRY 并且需要对数据库进行额外的查询。
最好的方法是什么?
编辑:最好在设置中定义 AUTH_PROFILE_MODULE 以指向基本模型,例如 AUTH_PROFILE_MODULE = 'profiles.baseprofile' 并且能够在每个上使用 user.get_profile()具有从同一基本配置文件派生的不同配置文件类别的用户。
I have several user profile models inherited from one base class like this:
class BaseProfile(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
...
class Meta:
abstract = True
class DoctorProfile(BaseProfile):
license_no = models.CharField(max_length=10)
...
class PharmacistProfile(BaseProfile):
pass
When I have a user instance, I would like to get their profile.
I don't feel like checking if the user has a profile one by one with sth. like this:
if user.doctorprofile_set.all().count() == 1:
return user.doctorprofile_set.all()[0]
elif user.pharmacistprofile_set.all().count() == 1:
return user.pharmacistprofile_set.all()[0]
...
for each profile is the best way as it is not DRY and requires extra queries on database.
What is the best way to do this?
edit: would be nice to define AUTH_PROFILE_MODULE in settings to point to the base model like AUTH_PROFILE_MODULE = 'profiles.baseprofile'
and be able to use user.get_profile() on every user with different profile classes derived from the same base profile.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将其设为 OneToOneField 而不是 FK,然后执行
user.doctorprofile
等。OneToOne 将抛出 Foo.DoesNotExist 或 Foo.MultipleObjectsReturned,但是,如果出现问题,请准备好捕获这些异常Make it a OneToOneField instead of a FK then do
user.doctorprofile
etc. The OneToOne will throw an Foo.DoesNotExist or Foo.MultipleObjectsReturned, though, if things go wrong, so be prepared to catch those exceptions