我想查询以从命令行获取详细信息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我想查询以从命令行获取详细信息相关的知识,希望对你有一定的参考价值。

在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_classDetailsOfEducationQualification类的属性,而不是Person类的属性,

所以您将无法从人对象访问它。

detail = DetailsOfEducationQualification.objects.get(id=1)
detail.course_class

上面的代码将返回ID为1的DetailsOfEducationQualificationcourse_class

如果您要从Person

对象访问course_class

然后您可以使用

person = Person.objects.get(id=1)
person.detailsofeducationqualification_set.first().course_class

person.detailsofeducationqualification_set

是所有将id为1的人作为外键的DetailsOfEducationQualification对象的查询集。

并且person.detailsofeducationqualification_set.first()将成为查询集的第一个元素。

希望有帮助。

以上是关于我想查询以从命令行获取详细信息的主要内容,如果未能解决你的问题,请参考以下文章

在单个查询中获取联系人的详细信息

sql [SQL查询片段]用于在命令行或通过R和其他工具使用SQL的快速代码段#tags:sql,R,text processing,命令li

MySQL - 查询临时表以从表中检索 2 行

查询以从表中仅获取一项

Spring Mongo 聚合查询以从 MongoDB 获取不同的国家名称和国家代码

选择查询以从 SQL Server 获取数据