django外键正向,反向查询

class Person_info(models.Model):
    person_id = models.AutoField(primary_key=True)
    person_name = models.CharField(verbose_name='姓名',max_length=32, unique=True)
    password = models.CharField(verbose_name='密码',max_length=32,unique=True)

    class Meta:
        verbose_name = '个人信息'
        verbose_name_plural = verbose_name
        db_table = 'person_info'
class File_info(models.Model):
    file_id = models.AutoField(primary_key=True)
    ffile_id = models.CharField(verbose_name='父文件id', max_length=64, null=True, blank=True)
    file_name = models.CharField(verbose_name='文件姓名', max_length=255, null=True, blank=True)
    person_id = models.ForeignKey('Person_info',to_field='person_id',verbose_name='个人信息主键id',related_name='fperson_id',on_delete = models.CASCADE)
    is_delete = models.CharField(choices=(('1', '是'), ('0', '否')), max_length=10, default='0', verbose_name='逻辑删除')

    class Meta:
        verbose_name = "文件信息"
        verbose_name_plural = verbose_name
        db_table = 'file_info'
class File_version(models.Model):
    fversion_id = models.AutoField(primary_key=True)
    file_id = models.ForeignKey('File_info',to_field='file_id',verbose_name='文件信息表主键id',related_name='fvfile_id',on_delete = models.CASCADE)
    person_id = models.ForeignKey('Person_info',to_field='person_id',verbose_name='个人信息主键id',related_name='fvperson_id',on_delete = models.CASCADE)
    update_time = models.DateTimeField(verbose_name='更新时间',default=datetime.datetime.now)
    file_url = models.CharField(verbose_name='文件地址',max_length=64, null=True, blank=True)
    type = models.CharField(verbose_name='文件类型',max_length=32, null=True, blank=True)
    size = models.IntegerField(null=True, blank=True)
    file_version = models.IntegerField(null=True, blank=True)
    file_remark = models.TextField(verbose_name='文件备注', null=True, blank=True)
    is_delete = models.CharField(choices=(('1', '是'), ('0', '否')), max_length=10, default='0', verbose_name='逻辑删除')

查询

file_msg_datas = models.File_info.objects.filter(ffile_id=str(file_id),is_delete="0")
for data in file_msg_datas:
    file_name = data.file_name
    folder_detailed_info = list(data.fvfile_id.filter(is_delete="0").order_by("-file_version").values())[0]
file_msg_datas = models.File_info.objects.filter(file_id=str(file_id), is_delete="0").first()
folder_detailed_info = list(file_msg_datas.fvfile_id.filter(is_delete="0").order_by("-file_version").values())
for detailed_info in folder_detailed_info:
    person_id = detailed_info["person_id_id"]
    operator = models.Person_info.objects.filter(person_id=person_id).first()
django–外键和表数据的操作

向多方表中添加数据:(多表中有一个字段是外键)
	O = One.objects.get(id=xxx)
	T = Two.objects.create(name="xxx", 外键_id=O.id)

查询多表中的数据:(一查多)
	O = One.objects.get(id=xxx)
    O.two_set.all()
    
查询一表中数据:(多查一)
	T = Two.objects.get(id=xxx)
	T.外建名

你可能感兴趣的:(python,django,mysql,python,数据库,django,python,后端)