django管理员列表_显示SQL连接数据

时间:2019-03-06 12:50:19

标签: django django-models django-admin

由现有php构成的页面已更改为python和Django。

现有查询

Select
    l.lawyer_idx,
    l.lawyer_email,
    lp.lawyer_profile_path,
    lp.lawyer_profile_name,
    lc.lawyer_company_name,
    lc.lawyer_company_address,
    lc.lawyer_detail_address,
    l.lawyer_agent
from lawyer l
left join lawyer_profile lp on l.lawyer_idx = lp.lawyer_idx
left join lawyer_company lc on l.lawyer_idx = lc.lawyer_idx
order by l.register_date desc;

我在models.py制作了每个表格

    models.py

    class Lawyer(models.Model):
     lawyer_idx = models.AutoField('ID', primary_key=True)
      lawyer_email = models.CharField('E-mail', unique=True, max_length=200)
     lawyer_agent = models.CharField(max_length=1, blank=True, null=True)

    class Meta:
       managed = False
       db_table = 'lawyer'


    class LawyerProfile(models.Model):
     lawyer_idx = models.AutoField('ID', primary_key=True)
     lawyer_profile_path = models.CharField(max_length=200, blank=True, null=True)
   lawyer_profile_name = models.CharField(max_length=100, blank=True, null=True)
.................

    class LawyerCompany(models.Model):
     lawyer_idx = models.AutoField('ID', primary_key=True)
     lawyer_company_name = models.CharField(max_length=100)
    ...............

我们想将以下查询放入 Django Admin.py的list_display部分是否可以显示在sql中加入的数据?

    Admin.py
    from django.contrib import admin
    from .models import Lawyer, LawyerCompany, LawyerProfile

    @admin.register(Lawyer)
    class LawyerAdmin(admin.ModelAdmin):

       list_per_page = 100
       **list_display = ['lawyer_idx', 'lawyer_email', 
'lawyer_agent', 'lawyer_profile_path', 'lawyer_profile_name', 'lawyer_company_name']**

1 个答案:

答案 0 :(得分:0)

您可以将查询添加为原始sql查询,但是那样就不会充分利用Django的ORM。

您没有在模型上明确定义任何关系,因此Django不知道您的模型如何关联。

如果lawyer_idx推荐律师,则可以将字段更改为OneToOneField / ForeignKey(无论如何,AutoField可能是错误的选择,因为值应该对应Lawyer模型中的变量,而不是自动生成)。还可以查看有关one-to-onemany-to-one关系的文档。

class LawyerProfile(models.Model):
     lawyer = models.OneToOneField(Lawyer, primary_key=True, 
         db_column="lawyer_idx", related_name="profile")

Django在访问相关数据时应自动执行联接;然后,您可以在Lawyer实例上通过其related_name .profile访问配置文件。在list_display选项中,您可以使用双下划线语法来访问相关数据:

list_display = ['lawyer_idx','lawyer_agent', 'profile__lawyer_profile_path']
list_select_related = ['profile']

如果添加list_select_related option,则Django将已经预先连接到指定的表,因此在访问相关数据时不会执行其他查询。