我正在使用django_rest framework
使用python3
+ django 1.11
构建API。
我创建了两个应用:一个是用于处理user profiles
的帐户应用,另一个是包含Employee
类的 hr :
在我的帐户应用中,我有两个类 - User
和Bio
分别定义如下:
class User(AbstractUser):
additional_info = models.CharField(max_length=100, null=True, blank=True)
provider = models.ManyToManyField('self', related_name='rel_doc')
def get_full_name(self):
full_name = '%s %s' % (self.last_name.upper(), self.first_name)
return full_name.strip()
class Bio(models.Model):
marital_status = models.ForeignKey(MaritalStatus, blank=True, null=True)
employment = models.ForeignKey(Employment, blank=True, null=True)
user = models.OneToOneField(User, blank=True, null=True)
id_type = models.ForeignKey(IdentificationType, null=True, blank=True)
main_id_type_no = models.CharField(max_length=50, null=True, blank=True)
birthday = models.DateField(default=date.today, blank=True, null=True)
siblings = models.CharField(max_length=20, blank=True, null=True)
no_in_household = models.CharField(max_length=20, blank=True, null=True)
ethnicity = models.ForeignKey(Ethnicity, null=True, blank=True)
blood_type = models.ForeignKey(BloodType, null=True, blank=True)
preferred_language = models.CharField(max_length=20, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
notes = models.CharField(max_length=200, db_index=True, blank=True)
gender = models.ManyToManyField(Sex)
em_contact = models.ForeignKey(EmergencyContact, null=True, blank=True)
em_c_relationship = models.ForeignKey(Relationship, null=True, blank=True)
address = models.ForeignKey(Address, null=True, blank=True)
我已将Bio
类导入Employee
类中的 hr 应用作为OneToOneField
。问题是我无法获得我创建的用户的名字和姓氏。
Employee
类
答案 0 :(得分:0)
我导入了:
from django.contrib.auth import get_user_model
from accounts.models import User
然后:
User = get_user_model()
class BioSerializer(serializers.ModelSerializer):
user= UserSerializer()
class Meta:
model= Bio
fields= ['user','marital_status','id_type','main_id_type_no','birthday','preferred_language','phone_number','gender']
# Nest Bio With User seriializer
class EmployeeSerializer(serializers.ModelSerializer):
# TODO: Define serializer fields here
bio = BioSerializer(read_only=True)
#user = UserSerializer()
class Meta:
model = Employee
# fields = ['user','tax_id_number','account_number','joining_date','designation','department','gender','marital_status','id_type','birthday','ethnicity','preferred_language','phone_number','em_contact','address']
fields = '__all__'