models.py
class Counties(BaseModel): countname = models.CharField(max_length=128, verbose_name="国家名称", null=True, blank=True) phoneareacode = models.IntegerField(verbose_name="电话区号", null=True, blank=True) code = models.IntegerField(verbose_name="国家code", null=True, blank=True) county_num = models.CharField(verbose_name="标号", max_length=10, null=True, blank=True) class Meta: verbose_name = "国家表" verbose_name_plural = verbose_name def __str__(self): return self.countname class Provinces(BaseModel): provincesname = models.CharField(max_length=128, verbose_name="城市名字") # counties = models.OneToOneField(to="Counties", # verbose_name="所属国家", # related_name="coun", # on_delete=models.CASCADE, # null=True, # blank=True) counties = TenantForeignKey(to="Counties", verbose_name="所属国家", related_name="coun", on_delete=models.CASCADE, null=True, blank=True) provinces_num = models.CharField(verbose_name="编号", max_length=10, null=True, blank=True) class Meta: verbose_name = "省份表" verbose_name_plural = verbose_name def __str__(self): return self.provincesname class City(BaseModel): cityname = models.CharField(max_length=128, verbose_name="城市名字", null=True, blank=True) provinces = TenantForeignKey(to="Provinces", verbose_name="所属省份", related_name="prov", on_delete=models.CASCADE, null=True, blank=True) city_num = models.CharField(max_length=10, verbose_name="城市标号", null=True, blank=True) class Meta: verbose_name = "城市表" verbose_name_plural = verbose_name def __str__(self): return self.cityname
serialzier.py
from models import (Jobs, Aivideomodel, Aiability, Question, Candidate, InvitationJobInterviewForm, Jobtype, Functions, City, Provinces, Counties)
class JobTypeSerializer(serializers.ModelSerializer):
functions_name = serializers.CharField(source='functions.function_name')
class Meta:
model = Jobtype
fields = ('id', 'jobtype_name', 'functions', 'functions_name')
class CitySerializer(serializers.ModelSerializer):
provinces_name = serializers.CharField(source='provinces.provincesname') # 跨一张表序列化省的名字
count_id = serializers.IntegerField(source='provinces.counties.id') # 跨两张表序列化国家的ID
count_name = serializers.CharField(source='provinces.counties.countname') # 跨两张表序列化国家的名字 注意 source='' 指定来源那张表那个字段 注意这些外键关联的表model必须要导入进来
class Meta:
model = City
fields = ('id', 'cityname', 'provinces_id', 'provinces_name', 'count_id', 'count_name')