简体   繁体   English

姜戈。 如何从views.py中的子模型获取字段?

[英]Django. How to get fields from child model in views.py?

How to get fields from child model in views.py ?如何从views.py子模型获取字段? For example, I've parent model BasicOrder and child model (who extends BasicOrder ) TouristVisa .例如,我有父模型BasicOrder和子模型(扩展BasicOrderTouristVisa

I'm using Django 2.0.2 and Python 3.6.1.我正在使用 Django 2.0.2 和 Python 3.6.1。 My models.py is:我的models.py是:

class BasicOrder(models.Model):

    user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE)
    status = models.PositiveIntegerField(_('Status'), choices=ORDER_STATUS, default=0)

    def __str__(self):
        return 'Order #{}'.format(self.id)


class TouristVisa(BasicOrder, models.Model):

    citizenship = models.ForeignKey(
        Citizenship, verbose_name=_('Citizenship'), on_delete=models.PROTECT
    )
    invitation_entry = models.PositiveSmallIntegerField(
        _('Invitation entry'), choices=INVITATION_ENTRY
    )

    class Meta:
        ordering = ['id']

Would be great to have access to field invitation_entry from child model ( TouristVisa ).能够访问来自子模型( TouristVisa )的字段invitation_entry TouristVisa I try this way in views.py :我在views.py尝试这种方式:

order = BasicOrder.objects.get(user=request.user.id)
print(order.invitation_entry)

But it's show error:但它的显示错误:

AttributeError: 'BasicOrder' object has no attribute 'invitation_entry' AttributeError: 'BasicOrder' 对象没有属性 'invitation_entry'

It's wrong, when TouristVisa inherits from BasicOrder it means it gets the fields user ans status as well, not the other way around.这是错误的,当TouristVisa 从BasicOrder 继承时,它意味着它也获得了用户和状态字段,而不是相反。 So, you can access the invitation_entry field but calling TouristVisa also because it's the only model where it exists.因此,您可以访问invitation_entry 字段,但也可以调用TouristVisa,因为它是唯一存在的模型。

Now, access to it like this:现在,像这样访问它:

order = BasicOrder.objects.get(user=request.user.id)
print(order.touristvisa.invitation_entry)

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

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