版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38570967/article/details/82077468
django中select_related方法用来查询一对一
和外键
对应的模型
Auto模型 (汽车)
class Auto(models.Model):
name_text = models.CharField("车名", max_length = 200)
car_license_date = models.DateField("车辆上牌时间")
carColorTag = models.ForeignKey(ColorTag, on_delete = None, verbose_name = '车辆颜色')
carEmissionLimitTag = models.ForeignKey(EmissionStandardTag,on_delete = None)
highlight = models.ManyToManyField(HeightLight, verbose_name = '亮点配置')
.filter()[(page - 1) * 10:10]
是用来分页的
查询外键对应的模型(one-to-one)
select_related(’属性名’)
#外键
foreign=['carColorTag', 'carEmissionLimitTag']
auto=Auto.objects.filter()[(page - 1) * 10:10].select_related(*foreign)
#获取外键对应的模型
color=auto.carColorTag
查询多对多(many-to-many)
prefetch_related(‘属性名’)
foreign=['carColorTag', 'carEmissionLimitTag']
auto=Auto.objects.filter()[(page - 1) * 10:10].select_related(*foreign).prefetch_related('highlight')
#获取外键对应的模型
color=auto.carColorTag
#得到一个queryset对象 多个highlight模型
highlight=auto.highlight.all()
for i in highlight:
pass