【问题标题】:How can I do join in django?我怎样才能加入django?
【发布时间】:2018-07-15 13:25:39
【问题描述】:

我正在使用 django,特别是现在使用 QuerySet,我遇到了一个非常大的问题。 所以,这是我的代码:

resources_rights = Resources_rights.objects.filter( group_id__in = groups )
resources = Resources.objects.filter( id__in = resources_rights__resource_id 

)

Resources_rights是指具有resource_idgroup_idreadwrite的模型em> 和 执行Resources 包含 last_modifynamedescription,当然还有 id .

所以,在 resource_rights 我保存了一些对象,每个人都有他的 resource_id

我会使用 resource_rights 中的 resource_id 字段过滤 Resources,但像我之前所做的那样是不可能的,因为第一个查询返回对象。

那么,我该怎么办?有一个运营商吗?

谢谢大家!

编辑: 型号是:

class Resources_rights(models.Model):
    resource_id = models.IntegerField( db_column='resource_id' )
    group_id = models.IntegerField(Groups, db_column='group_id' )
    read = models.BooleanField( db_column='read' )
    write = models.BooleanField( db_column='write' )
    execute = models.BooleanField( db_column='execute' )
    class Meta:
        db_table = u'sso_resource_permissions'

class Resources(models.Model):
    last_modify = models.DateField( db_column='last_modify' )
    resource_name = models.CharField(max_length=200, db_column='resource_name' )
    description = models.TextField()
    class Meta:
        db_table = u'sso_resources'

【问题讨论】:

    标签: django python-2.7 django-queryset


    【解决方案1】:

    尝试加入而不是做in:

    resources = Resources.objects.filter(resources_rights__group_id__in=groups)
    

    【讨论】:

    • 谢谢@Ivan,我正在尝试做的是正确的;但它返回给我一个错误:FieldError: Cannot resolve keyword 'resources_rights' into field。选项有:description、id、last_modify、resource_name。似乎它需要“resources_rights”作为资源字段
    • 为什么你有IntegerField作为resource_id?您应该将其更改为resource = models.ForeignKey(Resources, on_delete=models.CASCADE),然后使用我的答案中的查询。
    • 非常感谢伊万!你真的救了我!
    【解决方案2】:

    你应该看看values_list()。有了它们,您可以执行以下操作:

    resources_rights_ids = Resources_rights.objects.filter( group_id__in = groups ).values_list('id', flat=True)
    resources = Resources.objects.filter( id__in = resources_rights_ids )
    

    (未测试)

    【讨论】:

    • 你两个都对,但我会在 resources_rights 中的所有 Resources_rights 字段,因为我必须重用这个结果并再次查询以重做同样的事情是浪费。
    【解决方案3】:
    resources_rights = Resources_rights.objects.filter(group_id__in = groups).values_list('resource_id')
    resources = Resources.objects.filter( id__in = resources_rights )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2022-01-23
      • 2019-07-13
      • 2017-06-11
      相关资源
      最近更新 更多