2017-08-08 142 views
0

我有一个django tables2表运行得非常好,它只显示具有正确的Project Id的Querysets。我需要它来排除具有重复user_id的查询集。如何筛选特定列的唯一值的django tables2结果

例如:是

用户,1周,项目1

用户,每周2,项目1

用户B,1周,项目1

显示用户分配给项目1.(需要的结果是表行与一个&乙)

我到目前为止:

#models.py 
class Allocation(models.Model): 
    user_id = models.ForeignKey(Resource) 
    project_id = models.ForeignKey(Project) 
    week = models.DateField(default=timezone.now) 
    allocated_hours = models.IntegerField(default=0) 
    actual_hours = models.IntegerField(default=0) 

#tables.py 
class Project_Resource_table(tables.Table): 
    role = tables.Column(accessor='user_id.resource_type') 
    name = tables.Column(accessor='user_id.resource_name') 
    allocation = tables.Column(accessor='total_allocation') 

class Meta: 
    model = Allocation 
    exclude = ('id', 'user_id', 'project_id', 'week', 'allocated_hours', 'actual_hours') 
    sequence = ('role', 'name', 'allocation') 


#view (project_profile.py) 
def project_properties(request, offset): 
    try: 
     offset = int(offset) 
    except ValueError: 
     raise Http404() 
    project = Project.objects.get(pk=offset) 
    table = Project_Resource_table(Allocation.objects.filter(project_id=offset).order_by('user_id')) 



return render(request, '../templates/copacity/project_profile.html', { 
    'table': table, 
    }) 

我试过使用set(),但无济于事。还尝试了distinct(),但不适用于sqlite3数据库。也尝试用函数计算,但不断得到“期望的表或查询集,而不是功能”。任何建议还有什么要尝试?

+0

什么不适用于sqlite3 /独特的组合? – Jieter

+0

该文档说“只在PostgreSQL上,您可以传递位置参数(*字段)以指定DISTINCT应该应用的字段的名称。”我尝试了sqllite3和mysql,但都没有工作。我尝试了几个解决方法,但最终决定将该项目转换为PostgreSQL。它按照预期的那样工作。 – jonin

回答

0

您需要确保在创建表时通过QuerySet或者列表的字典。如果django-tables2抱怨得到一个函数,你给它一个函数,而不是从该函数返回的值。

+0

感谢您的回答。我同意你的陈述,但我希望能用一个函数编辑Queryset,以便在sqllite3数据库中复制“DISTINCT”调用。我确信有一种方法,但我最终放弃了,只是转换了我的分贝。 – jonin