如何在Django中获取多级数据

时间:2018-09-07 12:29:56

标签: django python-3.x

我是django框架的新手。我在mysql数据库中有4个表。我想从具有翻译表的主表和具有其翻译的城市表中获取数据。 我的模型。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     = 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 City(models.Model):
    country     = models.ForeignKey(Country, on_delete=models.CASCADE)

    class Meta:
        db_table = 'rh_cities'

class CityTranslation(models.Model):
    city        = models.ForeignKey(City, 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_city_translations'

这是我的views.py

Country.objects.filter(
                            is_featured=1,
                            countrytranslation__locale='en'
                        ).annotate(
                            name=F('countrytranslation__name')
                            totalCities=Count('city', distinct=True)
                        )

我想从城市表中获取所有带有外键country_id和城市名称的城市表。

0 个答案:

没有答案