我的查询得到了重复的结果。我的结果只有少数被重复。我使用django 1.8和sqlite作为我的数据库。重复的结果似乎是相同的条目ID#4和id#14。我已经使用sql lite浏览器进行了检查,并确认每个ID只有一个条目。我也在使用django_tables2。
这是我的models.py:
@python_2_unicode_compatible # only if you need to support Python 2
class Project(models.Model):
name = models.CharField(max_length=50)
jobNumber = models.CharField(max_length=8)
shopOut = models.DateTimeField(null=True)
shopIn = models.DateTimeField(null=True)
delivery = models.DateTimeField(null=True)
job1 = models.CharField(max_length=50, null=True)
job2 = models.CharField(max_length=50, null=True)
job3 = models.CharField(max_length=50, null=True)
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, default=101)
created_by = models.ForeignKey(User, related_name='Project_created_by')
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.ForeignKey(User, related_name='Project_modified_by')
modified_date = models.DateTimeField(auto_now=True)
assigned_to = models.ManyToManyField(User, related_name='Project_assigned_to')
def __str__(self):
return self.name
def save(self, *args, **kwargs):
if not self.id:
self.created_by = User.objects.get(id=1)
self.modified_by = User.objects.get(id=1)
super(Project, self).save(*args, **kwargs)
year = datetime.datetime.now().year
self.jobNumber = '{}{:04d}'.format(year, self.id)
self.modified_by = User.objects.get(id=1)
super(Project, self).save(*args, **kwargs)
这是我的table.py
class ProjectTable(tables.Table):
class Meta:
model = Project
exclude = ('shopOut', 'shopIn', 'delivery', 'job1', 'job2', 'job3', 'created_by', 'modified_by', 'modified_date')
attrs = {"class": "paleblue"}
这是我的views.py
def indexV(request):
model = Project.objects.values("id","name","jobNumber", "contractor", "assigned_to", "created_date")
table = ProjectTable(model)
RequestConfig(request).configure(table)
return render(request, 'project/index.html', {'table': table})
这是我的index.html:
{% block content %}
<h1>Projects</h1>
{% render_table table %}
{% endblock %}
如果还有其他需要的信息,请告诉我。如何删除查询中的重复条目?
答案 0 :(得分:1)
<强>更新强>
如果您确定您的数据有效,请致电only
在你的查询应该解决这个问题。我认为问题是你在查询集上调用values
后给出了dicts列表,但是你需要向ProjectTable提供一个查询集。
model = Project.objects.only("id","name","jobNumber", "contractor", "assigned_to", "created_date").distinct()