我是django框架中的新手。我在mysql数据库中有3个表。我想从主表中获取带有转换表和图像表的数据。我的model.py
class Country(models.Model):
#id = models.IntegerField(primary_key=True)
iso_code = models.CharField(max_length=2, unique=True)
slug = models.CharField(max_length=255, unique=True)
is_featured = models.IntegerField(max_length=1)
class Meta:
db_table = 'rh_countries'
class CountryTranslation(models.Model):
country_id = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
locale = models.CharField(max_length=2)
class Meta:
db_table = 'rh_countries_translations'
class CountryImage(models.Model):
country_id = models.ForeignKey(Country, on_delete=models.CASCADE)
image = models.CharField(max_length=255)
is_main = models.IntegerField(max_length=1)
class Meta:
db_table = 'rh_country_images'
现在我想通过locale和相关图像获取所有带翻译记录的国家/地区。如果有人知道,请给出解决方案。
您可以使用过滤和注释来执行此操作:
from django.db.models import F
Country.objects.filter(
countrytranslation__locale=mylocale
).annotate(
name=F('countrytranslation__name')
)
这将导致QuerySet
与所有Country
s(对于给定的Translation
有mylocale
)。这些Country
s将有一个额外的属性.name
,这是Country
的翻译名称。
因此,鉴于翻译存在,那么对于mylocale='en'
,这将导致QuerySet
,与Country(name='Germany', iso_code='de')
,并且对于mylocale='de'
,它将导致Country(name='Deutschland', iso_code='de')
(这里有点特殊格式,以演示它是如何工作的)。
注意:
ForeignKey
s通常不以_id
结尾。 Django会自动将_id
后缀添加到数据库列。外键本身位于Python / Django级别,表示为延迟加载属性。