简体   繁体   中英

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

How to get fields from child model in views.py ? For example, I've parent model BasicOrder and child model (who extends BasicOrder ) TouristVisa .

I'm using Django 2.0.2 and Python 3.6.1. My models.py is:

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 ). I try this way in 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'

It's wrong, when TouristVisa inherits from BasicOrder it means it gets the fields user ans status as well, not the other way around. So, you can access the invitation_entry field but calling TouristVisa also because it's the only model where it exists.

Now, access to it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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