如何在django中编写联接?

时间:2011-01-28 01:20:27

标签: django django-models django-queryset

如何在django中编写联接,我已经阅读了下面的django文档,但是联接对我的模型不起作用

http://docs.djangoproject.com/en/1.2/topics/db/queries/#lookups-that-span-relationships

和models / many_to_many /

和一些博客

我的模特:

class Profile(models.Model):
     name = models.CharField(max_length=50, primary_key=True)
     assign = models.CharField(max_length=50)
     doj = models.DateField()
     dob = models.DateField()

     class Meta:
        db_table = u'profile'

     def __str__(self):
         return  '%s %s %s %s' % ( self.name,self.assign,self.doj,self.dob)

     def __unicode__(self):
         return  u'%s %s %s %s' % ( self.name,self.assign,self.doj,self.dob)


     enter code here

class working(models.Model):
   w_name =models.ForeignKey(Profile, db_column='w_name')
   monday =  models.IntegerField(null=True, db_column='monday', blank=True)
   tuesday =  models.IntegerField(null=True, db_column='tuesday', blank=True)
   wednesday =  models.IntegerField(null=True, db_column='wednesday', blank=True)

   class Meta:
        db_table = u'working'

   def __str__(self):
         return  '%s %s %s %s' % ( self.w_name,self.monday,self.tuesday,self.wednesday)

   def __unicode__(self):
         return  u'%s %s %s %s' % ( self.w_name,self.monday,self.tuesday,self.wednesday)

我正在尝试在两个表profile和workingday之间进行连接

like m=working.objects.filter(name='sushanth').select_related()

如果我在查询之上运行,我会得到

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/django/db/models/manager.py", line 129, in filter
    return self.get_query_set().filter(*args, **kwargs)
  File "/usr/lib/pymodules/python2.6/django/db/models/query.py", line 498, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/usr/lib/pymodules/python2.6/django/db/models/query.py", line 516, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/usr/lib/pymodules/python2.6/django/db/models/sql/query.py", line 1675, in add_q
    can_reuse=used_aliases)
  File "/usr/lib/pymodules/python2.6/django/db/models/sql/query.py", line 1569, in add_filter
    negate=negate, process_extras=process_extras)
  File "/usr/lib/pymodules/python2.6/django/db/models/sql/query.py", line 1737, in setup_joins
    "Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'name' into field. Choices are:  monday,  tuesday, wednesday,  w_name

我需要查询我可以加入工作和个人资料的位置。

支持

select working.*,profile.assign,profile.doj from working join profile where name=w_name ;

我知道django不支持加入,内连接也适合我。

任何人都可以帮助.........................?

1 个答案:

答案 0 :(得分:4)

请格式化您的问题,以便代码可读({}图标),否则很难阅读。

working.objects.filter(name=将失败,因为您的working模型没有name字段。

来自您关联的文档:

  

Django提供强大而直观的功能   “跟随”关系的方式   查找,处理SQL JOIN   为你自动,在后面   场景。只是为了跨越关系   使用相关字段的字段名称   跨模型,以double分隔   下划线,直到你到达   你想要的领域。

转换为:

m = working.objects.filter(w_name__name='sushanth').select_related()