在Models.py文件中(我有此代码库)
class Person(models.Model):
sex_choices = (
('Male', 'Male'),
('Female', 'Female')
)
martial_choices = (
('Single', 'Single'),
('Married', 'Married'),
('Divorce', 'Divorce'),
('Widowed', 'Widowed')
)
name = models.CharField(max_length=200)
sex = models.CharField(choices=sex_choices, max_length=50)
martial_status = models.CharField(choices=martial_choices, max_length=50)
age = models.IntegerField()
def __str__(self):
return self.name
class DetailsOfEducationQualification(models.Model):
type_choice = (
("Government", "Government"),
("Private", "Private"),
("Anganwadi Center", "Anganwadi Center"),
)
education_proximity_choice = (
("0-5", '0-5km'),
('5-10', '5-10km'),
('10+', 'Above 10km'),
('Outside the state', 'Outside the state'),
)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
course_class = models.CharField(max_length=50, blank=True)
type_of_education_sector = models.CharField(choices=type_choice, max_length=50, blank=True)
education_facility_proximity = models.CharField(choices=education_proximity_choice, max_length=50, blank=True)
在Admin.py文件中(我有这个)
from .models import (
Person, DetailsOfEducationQualification
)
class DetailsOfEducationQualificationInline(admin.TabularInline):
model = DetailsOfEducationQualification
extra = 0
class PersonAdmin(admin.ModelAdmin):
fieldsets = [
(
'Personal Information', {
'fields':[
'name', 'sex', 'age', 'martial_status'
]
}
),
]
inlines = [
DetailsOfEducationQualificationInline
]
在查询shell中,由于DetailsOfEducationQualification模型与Person相关,因此我想获取人员'course_class':
就像在他的查询中一样:
person = Person.objects.get(id=1)
person.course_class
此代码出错,说人没有属性...如何从“人员”模型访问DetailsOfEducationQualification日期?
course_class是DetailsOfEducationQualification类的属性,而不是Person类的属性,
所以您将无法从人对象访问它。
detail = DetailsOfEducationQualification.objects.get(id=1)
detail.course_class
上面的代码将返回ID为1的DetailsOfEducationQualification的course_class。
如果您要从Person
对象访问course_class,然后您可以使用
是所有将id为1的人作为外键的DetailsOfEducationQualification对象的查询集。person = Person.objects.get(id=1) person.detailsofeducationqualification_set.first().course_class
person.detailsofeducationqualification_set
并且person.detailsofeducationqualification_set.first()将成为查询集的第一个元素。
希望有帮助。