试图获取location_profile以在__str__(django)中显示location.name

时间:2019-02-18 15:13:51

标签: django django-models django-rest-framework

我有以下2种型号:

class LocationProfile(models.Model):
    units                   = models.CharField(max_length=100,blank=True)
    location_notes          = models.TextField(blank=True)
    is_occupied             = models.BooleanField(default=False)

    def __str__(self):
        return self.location.name

class Location(models.Model):
    organization            = models.ForeignKey(Organization, on_delete=None)
    location_profile        = models.OneToOneField(LocationProfile, on_delete=None)
    name                    = models.CharField(max_length=255)
    address1                = models.CharField(max_length=100)

    def __str__(self):
        return self.name

我正在尝试获取LocationProfile来显示Location的名称,但是错误是: LocationProfile has no location

每个Location都有1个Location Profile,如果可能的话,我希望能够从django管理员的Location Profile下拉列表中选择Location转到Location Profile并选择Location。)

1 个答案:

答案 0 :(得分:0)

根据@ ashwin-bandes的建议,我已经弄清楚了。

我已经修改了模型,使其看起来像这样(可能有些过大,但是我想确保它能起作用):

class LocationProfile(models.Model):
    units                   = models.CharField(max_length=100,blank=True)
    location_notes          = models.TextField(blank=True)
    is_occupied             = models.BooleanField(default=False)

    def __str__(self):
        try:
            loc = Location.objects.get(location_profile=self.id)
            return loc.name
        except Location.DoesNotExist:
            return '%s' % self.id    

class Location(models.Model):
        organization            = models.ForeignKey(Organization, on_delete=None)
        location_profile        = models.OneToOneField(
                                    LocationProfile, 
                                    on_delete=None, 
                                    related_name="location", 
                                    related_query_name="location",
                                    primary_key=True,
                                    db_column='id'
                                )

基本上,它将最初在LocationProfile内创建Location,但是Location仅会看到LocationProfile ID,因为LP尚未设置为公司(或如果是这样,它将仅使用个人资料ID将其设置回。如果个人资料设置为公司,则用户将看到Location的名称,而不是个人资料ID。在管理员方面可能不是最优雅的,但是它可以满足我的需求。