我的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)
答案 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