I am trying to filter by the com_proc
variable but it does not work...
The complexity here is that the filter can contain more than once the same object. Here is my code:
class Act(models.Model):
com_proc=models.CharField(max_length=100, blank=True, null=True, default=None)
cs_1=models.ForeignKey(CodeSect, related_name='code_sect_1', blank=True, null=True, default=None)
cs_2=models.ForeignKey(CodeSect, related_name='code_sect_2', blank=True, null=True, default=None)
cs_3=models.ForeignKey(CodeSect, related_name='code_sect_3', blank=True, null=True, default=None)
class ActIds(models.Model):
propos_origine=models.CharField(max_length=4, blank=True, null=True, default=None)
act=models.ForeignKey(Act)
qs_acts=ActIds.objects.none()
len(qs_acts)
for act in ActIds.objects.all():
#loop over each cs variable
for nb in range(1,4):
code_sect=getattr(act.act, "cs_"+str(nb))
if code_sect is not None:
qs_acts._result_cache.append(act)
print "qs_acts"
for act in qs_acts:
print act.pk, act.act.com_proc, act.propos_origine
I use a dynamic queryset
with _result_cache
because each object can be present in the filter up to three times (once for each cs
variable). I don't know how to reproduce that with a normal filtering.
Output:
9429 Oral procedure COM
9429 Oral procedure COM
9697 Written procedure COM
12352 Written procedure COM
12362 Oral procedure COM
Code:
...
print filter_vars_periods
Output:
{'act__com_proc': 'Written procedure', 'propos_origine': 'COM', 'act__adopt_conseil__gte': datetime.date(2009, 12, 1), 'act__adopt_conseil__lte': datetime.date(2013, 12, 31)}
Code:
temp_filter=qs_acts.filter(**filter_vars_periods)
for act in temp_filter:
print act.pk, act.act.com_proc, act.propos_origine
Output:
9429 Oral procedure COM
9429 Oral procedure COM
9697 Written procedure COM
12352 Written procedure COM
12362 Oral procedure COM
You can see that the filtering by the com_proc="Written procedure"
did not work, I get the same queryset at the end. Why?
Edit
I think I know why two successive filterings do not give the expected output:
Chaining multiple filter() in Django, is this a bug?
It is said that using two filters is not the equivalent of the logical AND
but is the equivalent of the logical OR
. So that could be the reason why my second filter doesn't filter anything...
Anyway, I still don't know how to solve my problem :(.