简体   繁体   English

使用Django查询获取相关模型

[英]Get related model with Django query

Can you please help me with Django query. 您能帮我用Django查询吗? I am new in this stuff and I am trying to optimize the queries in my site. 我是新手,我正在尝试优化网站中的查询。 Below is the current case: I use the standard User model as base model and have 3 types of users, which are related with it: A, B and C. "User" can be related with only one of these 3 model. 下面是当前情况:我使用标准的用户模型作为基本模型,并具有3种与之相关的用户:A,B和C。“用户”只能与这3种模型之一相关。 Currently I have a list with instance from Model D, which is related with User as well. 目前,我有一个列表,其中包含来自Model D的实例,该实例也与User有关。 Below is my code 下面是我的代码

D = D.objects.all()
for element in D:
try:
     results.append(element.user.A)
except:
    try:
        results.append(element.user.B)
    except:
        results.append(element.user.C)

As you already noticed, this solution is not the best one in this case(and maybe this is the worst). 正如您已经注意到的,在这种情况下,这种解决方案不是最佳解决方案(也许这是最糟糕的)。 I appreciate any help. 感谢您的帮助。 Thanks in advance. 提前致谢。

Edit: Here is and my models: 编辑:这是我的模型:

class A(models.Model)
    facebook_id = models.CharField(max_length=20, blank=True, null=True)
    user = models.OneToOneField(User, unique=True)
    ...

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

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

class D(models.Model):
    user = models.ForeignKey(User)
    F = models.ForeignKey(F)

I actually had the very same issue some time ago, and if I were to do it again, I'd follow remy_g's hint no matter how different the models are. 实际上,我前段时间也遇到过同样的问题,如果我要再做一次,无论模型有多大差异,我都会遵循remy_g的提示。

That being said, you could use hasattr() instead of the messy try / except nest. 话虽这么说,但您可以使用hasattr()代替混乱的try /除了nest。

http://docs.python.org/2/library/functions.html#getattr http://docs.python.org/2/library/functions.html#getattr

What it would look like : 它看起来像什么:

D = D.objects.all()
for element in D:
    if hasattr(element.user, "A"):
        results.append(element.user.A)
    elif hasattr(element.user, "B"):
        results.append(element.user.B)
    elif hasattr(element.user, "C"):
        results.append(element.user.C)

You can improve this to your liking but you get the idea... 您可以根据自己的喜好对此进行改进,但是您知道了...

Hope this helps, 希望这可以帮助,

Regards, 问候,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM