django中 一對一(one-to-one)和多對一(many-to-many)查詢

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章