Skip to content
Snippets Groups Projects

Resolve "two visits with the same dates"

Merged Piotr Gawron requested to merge 369-two-visits-with-the-same-dates into master
3 files
+ 41
4
Compare changes
  • Side-by-side
  • Inline
Files
3
+ 5
4
@@ -126,16 +126,17 @@ class Visit(models.Model):
self.save()
return
@receiver(post_save, sender=Visit)
def check_visit_number(sender, instance, created, **kwargs):
# no other solution to ensure the visit_number is in cronological order than to sort the whole list if there are future visits
# no other solution to ensure the visit_number is in chronological order than to sort the whole list if there are future visits
visit = instance
if visit.subject is not None: #not sure if select_for_update has an effect, the tests work as well without it
#new visit, sort only future visit respect to the new one
if created:
visits_before = Visit.objects.select_for_update().filter(subject=visit.subject).filter(datetime_begin__lt=visit.datetime_begin).count()
# we need to sort the future visits respect to the new one, if any
visits = Visit.objects.select_for_update().filter(subject=visit.subject).filter(datetime_begin__gte=visit.datetime_begin).order_by('datetime_begin','datetime_end')
visits = Visit.objects.select_for_update().filter(subject=visit.subject).filter(datetime_begin__gte=visit.datetime_begin).order_by('datetime_begin','id')
with transaction.atomic(): #not sure if it has an effect, the tests work as well without it
for i, v in enumerate(visits):
expected_visit_number = (visits_before + i + 1)
@@ -143,10 +144,10 @@ def check_visit_number(sender, instance, created, **kwargs):
Visit.objects.filter(id=v.id).update(visit_number=expected_visit_number) # does not rise post_save, we avoid recursion
if v.id == visit.id: #if the iteration visit is the same that the instance that produced the signal call
#this ensures that the upper saved object is also updated, otherwise, refresh_from_db should be called
visit.visit_number = v.visit_number
visit.visit_number = v.visit_number
else:
#if visits are modified, then, check everything
visits = Visit.objects.select_for_update().filter(subject=visit.subject).order_by('datetime_begin','datetime_end')
visits = Visit.objects.select_for_update().filter(subject=visit.subject).order_by('datetime_begin','id')
with transaction.atomic():
for i, v in enumerate(visits):
expected_visit_number = (i+1)
Loading