날짜 필드와 별도의 시간 필드가있는 django 모델이 있습니다. 필터를 사용하여 현재 레코드의 날짜 시간보다 작은 날짜 / 시간으로 최신 레코드의 값을 찾으려고합니다.
주석 / 집계를 사용하여 날짜 및 시간 필드를 하나로 결합한 다음 필터를 수행하려면 어떻게해야합니까?
models.py
class Note(models.model):
note_date = models.DateField(null=True)
note_time = models.TimeField(null=True)
note_value = models.PositiveIntegerField(null=True)
def get_last(n):
"""
n: Note
return: Return the note_value of the most recent Note prior to given Note.
"""
latest = Note.objects.filter(
note_date__lte=n.note_date
).order_by(
'-note_date', '-note_time'
).first()
return latest.note_value if latest else return 0
이렇게하면 이전 날짜의 모든 메모가 반환되지만 같은 날짜에 오후 3시와 오후 1시에 두 개의 메모가 있고 오후 3시 메모를 함수에 보내면 오후 1시 메모의 값을 얻고 싶습니다. . 비교를 위해 두 필드를 하나로 주석 처리하는 방법이 있습니까? 아니면 원시 SQL 쿼리를 수행해야합니까? 날짜 및 시간 구성 요소 Concat
를 문자열에 사용할 수있는 방법과 유사하게 하나로 변환하는 방법이 있습니까?
Note.objects.annotate(
my_dt=Concat('note_date', 'note_time')
).filter(
my_dt__lt=Concat(models.F('note_date'), models.F('note_time')
).first()
models.Q
여기를 사용하여 답을 찾았 습니다 : django에서 결합 된 날짜 및 시간 필터링
Note.objects.filter(
models.Q(note_date__lt=n.note_date) | models.Q(
note_date=n.note_date,
note_time__lt=n.note_time
)
).first()
올바른 기준으로 검색하지 않은 것 같습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다