从通用视图引用其他模型

时间:2016-12-05 18:03:22

标签: django django-views

我很难找到答案。也许它可能,也许它不是。如果我有另一个模型的引用,让我们说model1.customer_id = 123,我怎样才能在listview中使用该引用来显示model2.company_name,其中model1模型的主键(也称为customer_id)也是== 123?

两种型号都包含各自的主键。

class TblCompanies(models.Model):
    company_name = models.CharField(db_column='Company Name', max_length=50)
    billing_address = models.CharField(db_column='Billing Address', max_length=255, blank=True, null=True)
    company_id = models.AutoField(db_column='Company ID', primary_key=True)
    notes = models.TextField(db_column='Notes', blank=True, null=True)

class TblServiceRecords(models.Model):
    sr_id = models.CharField(db_column='SR ID', primary_key=True, max_length=50)  
    company_id = models.ForeignKey('TblCompanies', on_delete=models.CASCADE) 
    date_entered = models.DateTimeField(db_column='Date Entered', blank=True, null=True)  
    date_updated = models.DateTimeField(db_column='Date Updated', blank=True, null=True)

2 个答案:

答案 0 :(得分:1)

你应该展示你的模特。 customer_id可能是ForeignKey:

class Model1(models.Model):
    ...
    customer = models.ForeignKey('model2')

所以在你的模板中你可以这样做:

{{ model_1_instance.customer.company_name }}

答案 1 :(得分:1)

试试这个会起作用:

class Model1(models.Model):    
    customer_id = = models.IntegerField(primary_key=True)
    customer = models.ForeignKey('model2',db_column='customer',related_name='customer')
class Model2(models.Model):    
    customer_id1 = = models.IntegerField(primary_key=True)
    company_name = models.CharField(max_length=50)

    model1_instance = Model1.objects.get(customer_id=123)
     in template use following code
    {{ model1_instance.customer.company_name }}