使用外键从django中的2级深度关系中获取关联表数据

时间:2013-10-31 00:04:27

标签: django django-models

这是我的问题,我试图找出成为django的初学者

  1. 我想让user app知道城市表使用外键连接到国家/地区表格中的国家/地区。用户表有city_id列。请注意,用户已经登录。我已经到了城市但不是国家

  2. 之后在我的instructor应用中,我获得了与国家/地区列currency_id相关联的货币。

  3. 这就是我所拥有的。

    /instructors/model.py

    from django.db import models
    from locations.models import City, Country
    
    class Class(models.Model):
       ...
       city = models.ForeignKey(City, null=True, blank=True)
    
    
    class Currency(models.Model):
        name = models.CharField(max_length=20)
        symbol = models.CharField(max_length=7, help_text="Code HTML")
        initials = models.CharField(max_length=5, help_text="e.g. : CLP (Chilean Pesos)")
    
        class Meta:
            verbose_name_plural = "currencies"
    
        def __unicode__(self):
            return self.name
    
        def get_label(self):
            return '%s (%s)' % (self.symbol, self.initials)
    

    /users/model.py

    class User(AbstractUser):
        ...
        city = models.ForeignKey(City, blank=True, null=True, db_index=True)
        ...
    
        def get_locality(self):
            locality = ''
            if self.location:
                locality = '%s, %s, %s' % (self.location.name, self.location.city.name, self.city.country.name)
            elif self.city:
                locality = '%s, %s' % (self.city.name, self.city.country.name)
            return locality
    

    /locations/model.py

    from django.db import models
    
    class Country(models.Model):
        code = models.CharField(max_length=3)
        name = models.CharField(max_length=100)
        order = models.IntegerField(default=0)
        currency_id = models.IntegerField(max_length=3)
    
        class Meta:
            verbose_name_plural = "countries"
    
        def __unicode__(self):
            return self.name
    
    
    class City(models.Model):
        country = models.ForeignKey(Country)
        name = models.CharField(max_length=100)
        order = models.IntegerField(default=0)
    
        class Meta:
            verbose_name_plural = "cities"
    
        def __unicode__(self):
            return "%s, %s" % (self.name, self.country)
    
    
    class Location(models.Model):
        city = models.ForeignKey(City)
        name = models.CharField(max_length=100)
    
        class Meta:
            verbose_name_plural = "locations"
    
        def __unicode__(self):
            return "%s, %s" % (self.name, self.city)
    

0 个答案:

没有答案