在查询集中获取嵌套对象的特定值以进行序列化

时间:2017-12-04 13:35:27

标签: python django models

我的django项目中有两个模型,分别是Followup和User,每个后续都有一个映射到它的用户实例[actor field]。发生的事情是当我运行此代码时,我默认获得了actor的主键我需要获取 first_name 字段,该字段位于用户模型中,用于从后续提取的所有行

result = Followup.objects.filter(lead_name = lead).only('lead_name','followup','comments','actor')
plan = PlanType.objects.filter(lead_id = lead)
response["followup"] = serializers.serialize('json', result)

跟进模式

class Followup(TimeStampedModel):
lead_name = models.ForeignKey(
    LeadInfo,
    on_delete=models.CASCADE,
    null=True
)
followup = models.DateField(
    blank=False,
    verbose_name='Follow up date'
)
comments = models.TextField(blank=True, verbose_name='Comments')
actor = models.ForeignKey(
    User,
    blank=True,
    limit_choices_to={'is_staff': True},
    on_delete=models.CASCADE,
    null=True,
    verbose_name='Actor'
)
class Meta:
    verbose_name = 'followup'
    verbose_name_plural = 'followups'

def __str__(self):
    return '{}'.format(self.lead_name)

用户模型

class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(_('First Name'), max_length=120, blank=True)
last_name = models.CharField(_('Last Name'), max_length=120, blank=True)
email = models.EmailField(_('email address'), unique=True, db_index=True)
is_staff = models.BooleanField(_('staff status'), default=False,
                               help_text='Designates whether the user can log into this admin site.')

is_active = models.BooleanField('active', default=True,
                                help_text='Designates whether this user should be treated as '
                                          'active. Unselect this instead of deleting accounts.')
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

USERNAME_FIELD = 'email'
objects = UserManager()

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')
    ordering = ('-date_joined', )

def __str__(self):
    return str(self.email)

def get_full_name(self):
    """
    Returns the first_name plus the last_name, with a space in between.
    """
    full_name = '{} {}'.format(self.first_name, self.last_name)
    return full_name.strip()

def get_short_name(self):
    "Returns the short name for the user."
    return self.first_name.strip()

1 个答案:

答案 0 :(得分:0)

由于django不支持序列化相关字段。尝试Django Rest,我认为这将满足您的需求。 Django Rest Serializers

在你的情况下,也许: Django Rest Method fields