访问相关模型

时间:2014-11-09 21:00:11

标签: django django-models

我有这4个型号。

class Department(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)


class PhoneUser(models.Model):
    name = models.CharField(_('name'), max_length=100)
    department = models.ForeignKey(Department, blank=True, null=True, 
                                   related_name='users', related_query_name='user',
                                   verbose_name=_('Department'))


class Extension(models.Model):
    number = models.CharField(_('Extension'), max_length=settings.EXTENSION_MAX_LENGTH, blank=False)
    user = models.ForeignKey(PhoneUser, null=True, blank=True, related_name='extensions',
                         related_query_name='extension', verbose_name=_('Phone User'))


class PhonePIN(models.Model):
    pin = models.CharField(_('PIN'), max_length=settings.PIN_MAX_LENGTH)
    user = models.ForeignKey(PhoneUser, null=True, 
                             blank=True, related_name='pins', related_query_name='pin',
                             verbose_name=_('Phone User'))

我想从Department对象中获取Extension和PhonePIN对象的列表,尽管它们与PhoneUser对象的关系。

是否可以在Django中执行此操作?

1 个答案:

答案 0 :(得分:2)

documentation on making queries已完整回答。

Extension.objects.filter(user__department__name='my department')
PhonePIN.objects.filter(user__department__name='my department')

或者,如果您已有Department对象:

Extension.objects.filter(user__department=my_department)
PhonePIN.objects.filter(user__department=my_department)

这将为您节省一个JOIN。