从django的用户模型扩展后,如何在自定义模型中获取fname和lname

时间:2018-03-26 08:27:44

标签: django python-3.x django-models django-rest-framework

我的User模型类位于accounts.models。然后,我在Employee中创建了hr.models课程,并将user添加为ForeignKeyField。如何在Employee类中实现一个方法来查看名字和姓氏?

class User(AbstractUser):
    additional_info = models.CharField(max_length=100, null=True, blank=True)
    provider = models.ManyToManyField('self', related_name='rel_doc')

    def __str__(self):
        return "%s %s (%s)" % (self.first_name, self.last_name, self.username)

hr.models

class Employee(models.Model):
    user = models.ForeignKey(User, related_name='users',
                             on_delete=models.CASCADE)
    gender = models.ForeignKey(Sex)
    dob = models.DateField(blank=True, null=True)
    company = models.ForeignKey(
        'hr.Company',
        verbose_name='Company',
        related_name='companies',
        null=True, blank=True,
    )


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

3 个答案:

答案 0 :(得分:0)

您有一个用户的外键,您可以使用点符号跟随它:

print(self.user.firstname, self.user.lastname)

答案 1 :(得分:0)

将以下方法添加到Employee类

def get_first_name(self):
    return self.user.first_name

def last_name(self):
    return self.user.last_name

def get_full_name(self):
    return self.user.get_full_name()

请参阅此link了解详情

答案 2 :(得分:0)

在serializers.py中导入: from django.contrib.auth import get_user_model 然后在user = UserSerializer()

中定义EmployeeSerializer

from django.contrib.auth import get_user_model

class EmployeeSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    class Meta:
        model = Employee
        # fields = ['id', 'user', 'dob', 'gender', 'hr_number', 'company', 'marital_status', 'identification_type',
        #             'tax_id_number','joining_date', 'designation', 'department']
        fields = '__all__'

之后我在视图中定义:

class ListEmployees(generics.ListAPIView):
    """
    List all employees.
    """
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer