Django 新手 models

class DP(models.Model):
    dp_id = models.AutoField(verbose_name='部门编号', db_column='dp_id', primary_key=True)
    name = models.CharField(verbose_name='部门名称', db_column='name', max_length=32, unique=True)

    class Meta:
        db_table = 'rep_test_department'

    def __unicode__(self):
        return self.name


class Users(models.Model):
    userId = models.AutoField(verbose_name='编号', db_column='userId', primary_key=True)
    username = models.CharField(verbose_name='姓名', db_column='username', max_length=32)
    dp = models.ForeignKey('DP', on_delete=models.SET_NULL, null=True)

    class Meta:
        db_table = 'rep_test_user'

    def __unicode__(self):
        return self.username


class Years(models.Model):
    yearId = models.AutoField(verbose_name='年ID', db_column='yearId', primary_key=True)
    yearname = models.CharField(verbose_name='年', db_column='yearname', max_length=32)

    class Meta:
        db_table = 'rep_test_year'

    def __unicode__(self):
        return self.year


class Tables(models.Model):
    tableId = models.AutoField(verbose_name='年ID', db_column='tableId', primary_key=True)
    path = models.CharField(verbose_name='地址', db_column='path', max_length=256)
    year = models.ForeignKey(to='Years', related_name='NewYear', on_delete=models.SET_NULL, null=True)
    user = models.ForeignKey(to='Users', on_delete=models.CASCADE)
    dp = models.ForeignKey(to='DP', on_delete=models.CASCADE)

    class Meta:
        db_table = 'rep_test_tables'
select a.yearId,a.yearname,b.path,c.username,d.`name` as DepartName
from rep_test_year a left join rep_test_tables b on a.yearId = b.year_id left JOIN rep_test_user c on c.userId  b.user_id left join rep_test_department d on d.dp_id = c.dp_id

数据库模型建立是上面这样的,希望能实现上面的SQL语句结果。不知models语句应该怎么写。也有可能是模型建立的有问题。请高手指导下。在线等.....

评论 0