class AppleModel(models.Model): id=models.AutoField(primary_key=True) app_name=models.CharField(max_length=50) class Meta: db_table='tbl_apple' class PickleModel(models.Model): pid=models.AutoField(primary_key=True) app=models.ForeignKey(to="AppleModel",on_delete=models.CASCADE,related_name="pickle") color=models.CharField(max_length=20) class Meta: db_table='tbl_pickle'
什么叫正向:由外键所在表(从表) 查询主表对象或者主表字段就叫正向查询
示例:
filter格式外键所在模型类(从表)的外键字段名__主表字段名
# 查到的是苹果对象,从表查主表对象
PickModel.objects.filter(app__app_name="red").values()
反向查询:由主表对象查询从表对应的关联主表对象的从表对象或者字段 即为反向查询,如根据班级对象找到一班对应的名字为张三的学生对象信息
# 查到的是Pickle对象
filter格式:主表类的relaetd_name__从表字段名
Apple.objects.filter("pickle__color="red").values()
下面演示反向查询的两种方式使用related_name 和不使用related_name
使用related_name 则查询变为
主表对象.related_name的值.all() # 如果一对一直接不使用all:
from platformapp.models import *
app=AppleModel.objects.first()
app.pickle
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x000001C5E0494048>
app.pickle.all()
<QuerySet [<PickleModel: PickleModel object (1)>, <PickleModel: PickleModel object (2)>]>
app.pickle.all().values()
<QuerySet [{'pid': 1, 'app_id': 7, 'color': 'red'}, {'pid': 2, 'app_id': 7, 'color': 'black'}]>
反向查不使用related_name
# 这里注意表外键未使用related_name参数
app=models.ForeignKey(to="AppleModel",on_delete=models.CASCADE)
查询格式:
主表对象.从表模型类小写_set:
class AppleModel(models.Model): id=models.AutoField(primary_key=True) app_name=models.CharField(max_length=50) class Meta: db_table='tbl_apple' class PickleModel(models.Model): pid=models.AutoField(primary_key=True) app=models.ForeignKey(to="AppleModel",on_delete=models.CASCADE) color=models.CharField(max_length=20) class Meta: db_table='tbl_pickle'
from platformapp.models import *
app=AppleModel.objects.first()
app.picklemodel_set.all()
<QuerySet [<PickleModel: PickleModel object (1)>, <PickleModel: PickleModel object (2)>]>
app.picklemodel_set.all().values()
<QuerySet [{'pid': 1, 'app_id': 7, 'color': 'red'}, {'pid': 2, 'app_id': 7, 'color': 'black'}]>