def get_queryset(self):
# current_date = datetime(2024, 9, 2, 12, 56, 54, 324893).today()
current_date = datetime.today()
# get the booking data from the current date --------- requested_datetime is when the patient has scheduled the booking for
booking_data = PatientBooking.objects.annotate(
admission_datetime=F('requested_admission_datetime'),
delivery_datetime=F('estimated_due_date'),
fully_dilation_datetime=ExpressionWrapper(
F('estimated_due_date') - timedelta(days=(1)),
output_field=DateTimeField()
),
source=Value('booking', output_field=CharField())
).filter(status="ACCEPTED",
admission_datetime__date=current_date
)
# get the patient data from the current date ---- based on when the patient record is created_at
patient_data = PatientDetails.objects.annotate(
admission_datetime=F('created_at'),
delivery_datetime=F('estimated_due_date'),
fully_dilation_datetime=F('patient_fully_dilated'),
source=Value('patient', output_field=CharField())
).filter(status="ACTIVE",
admission_datetime__date=current_date
)
# combine the record in one queryset using union on the required fields only
combined_queryset = booking_data.values('first_name', 'last_name', 'delivery_type', 'date_of_birth',
'admission_datetime', 'delivery_datetime', 'fully_dilation_datetime', 'source'
).union(
patient_data.values('first_name', 'last_name', 'delivery_type', 'date_of_birth',
'admission_datetime', 'delivery_datetime', 'fully_dilation_datetime', 'source'
)
).order_by('first_name', 'last_name', 'date_of_birth')
# if records in both the model matches---- then consider it as same patient and consider the record where the source=patient
combined_queryset = combined_queryset.distinct(
'first_name', 'last_name', 'date_of_birth'
)
return combined_queryset
This is my queryset. I have two models PatientDetails and PatientBooking both models have different numbers of fields and names I want to get a single queryset with specific fields from both tables.
So I first annotate the field name and then perform union to it. To get a single queryset with field name (‘first_name’, ‘last_name’, ‘delivery_type’, ‘date_of_birth’,
‘admission_datetime’, ‘delivery_datetime’, ‘fully_dilation_datetime’, ‘source’) . Till now everything is working fine and I’m getting the desired result.
But after getting the result from both the models in a single queryset . Now I want to get distinct record based on (‘first_name’, ‘last_name’,’date_of_birth’)
I tried
combined_queryset = combined_queryset.distinct(
'first_name', 'last_name', 'date_of_birth'
)
but it is not working.
What I’m doing wrong can anyone tell me.