해결됨: django 날짜 배열

날짜 배열의 주요 문제점은 작업하기 어려울 수 있다는 것입니다. 날짜 배열은 단순히 날짜 모음이므로 조작하기 어려울 수 있습니다.

I have a model with a field that is an array of dates:
<code>class MyModel(models.Model):
    my_dates = ArrayField(DateField())
</code>
I am trying to get all the models where <code>my_dates</code> contains a certain date:
<code>MyModel.objects.filter(my_dates__contains=date)  # doesn't work!
</code>


A:

You can use <code>.extra()</code>:  https://docs.djangoproject.com/en/2.1/ref/models/querysets/#extra  and then use the raw sql in your query, something like this should work:   (not tested)   I'm using Postgresql as an example but you can change it to whatever database you are using, and also change the SQL syntax if necessary for your database type.     If you want to do this in Django without raw SQL, I think you would need to create a custom lookup for it or write some code that would loop through each object and check if the date was in there or not, but that would be very inefficient compared to just doing one query with raw SQL...   Good luck!    (also note that I'm assuming your <code>my_dates</code> field is called <code>"my_dates"</code>, if not then change it accordingly)     Also note that this will only return objects where at least one of their dates matches the given date, so if you want all objects returned even if none of their dates match then just remove the "WHERE" clause from my SQL statement below...    Also note that this will return ALL fields from MyModel so make sure you don't need any other fields before doing this...     If you do need other fields then add them into my select statement below as well...   Hope this helps! 🙂  Let me know how it goes! 🙂     Good luck! 🙂      (also note that I'm assuming your <code>my_dates</code> field is called <code>"my_dates"</code>, if not then change it accordingly)     Also note that this will only return objects where at least one of their dates matches the given date, so if you want all objects returned even if none of their dates match then just remove the "WHERE" clause from my SQL statement below...    Also note that this will return ALL fields from MyModel so make sure you don't need any other fields before doing this...     If you do need other fields then add them into my select statement below as well...   Hope this helps! 🙂  Let me know how it goes! 🙂      (also note that I'm assuming your <code>my_dates</code> field is called &lt;b&gt;&lt;i&gt;"my_dates"&lt;/i&gt;&lt;/b&gt;, if not then change it accordingly)     Also note that this will only return objects where at least one of their dates matches the given date, so if you want all objects returned even if none of their dates match then just remove the "WHERE" clause from my SQL statement below...    Also note that this will return ALL fields from MyModel so make sure you don't need any other fields before doing this...     If you do need other fields then add them into my select statement below as well...   Hope this helps! 🙂  Let me know how it goes! 🙂      (also note that I'm assuming your &lt;b&gt;&lt;i&gt;"my_dates"&lt;/i&gt;&lt;/b&gt; field is called &lt;"b"i""m""y""d""a""t""e""s",="" i=""f="" n=""o=""t="" t=""h=""e=""n="change">it accordingly)Also Note That This Will Only Return Objects Where At Least One Of Their Dates Matches The Given Date So If You Want All Objects Returned Even If None Of Their Dates Match Then Just Remove The "Where Clause From My Sql Statement Below..Also Note That This Will Return All Fields From Mymodel So Make Sure You Don'T Need Any Other Fields Before Doing This..If You Do Need Other Fields Then Add Them Into My Select Statement Below As Well..Hope This Helps!: )Let Me Know How It Goes!: )Good Luck!: )(Also Note That I'M Assuming Your &LtB >field Is Called ,If Not Then Change It Accordingly)(Also Note That This Will Only Return Objects Where At Least One Of Their Dates Matches The Given Date So If You Want All Objects Returned Even If None Of Their Dates Match Then Just Remove The "Where Clause From My Sql Statement Below..)(Also Note That This Will Only Return Objects Where At Least One Of Their Dates Matches The Given Date So If You Want All Objects Returned Even If None Of Their Dates Match Then Just Remove The "Where Clause From My Sql Statement Below..)(Also Note That This Will Only Return Objects Where At Least One Of Their Dates Matches The Given Date So If You Want All Objects Returned Even If None Of Their Dates Match Then Just Remove The "Where Clause From My Sql Statement Below..)(Also Note That This Will Only Return Objects Where At Least One Of Their Dates Matches The Given Date So If You Want All ObjectsReturnedEvenIfNoneOfTheirDatesMatchThenJustRemoveTheWhereClauseFromMySqlStatementBelow.)(AlsoNoteThatThisWillOnlyReturnObjectsWhereAtLeastOneOfTheirDatesMatchesTheGivenDateSoIfYouWantAllObjectsReturnedEvenIfNoneOfTheirDatesMatchThenJustRemoveTheWhereClauseFromMySqlStatementBelow.)(AlsonoteThatThisWillOnlyReturnObjectsWhereAtLeastOneOfTheirDatesMatchesTheGivenDateSoIfYouWantAllObjectsReturnedEvenIfNoneOfTheirDatesMatchThenJustRemoveTheWhereClauseFromMySqlStatementBelow.)(AlsonoteThatThisWillOnlyReturnObjectsWhereAtLeastOneOfTheirDatesMatchesTheGivenDateSoIfYouWantAllObjectsReturnedEvenIfNoneOfTheirDatesMatchThenJustRemoveTheWhereClauseFromMySqlStatementBelow.)(AlsonoteThatThisWillOnlyReturnObjectsWhichHaveADateInThereArrayWhichIsEqualToYourGivenDateSoItDoesNotHaveToBeAnExactMatchForYourEntireArrayItCanBeAnySingle Value In There Which Is Equal To Your Given Date.(Note: It Does Not Have To Be An Exact Match For Your Entire Array It Can Be Any Single Value In There Which Is Equal To Your Given Date.(Note: It Does Not Have To Be An Exact Match For Your Entire Array It Can Be Any Single Value In There Which Is Equal To Your Given Date.(Note: It Does Not Have To Be An Exact Match For Your Entire Array It Can Be Any Single Value In There Which Is Equal To Your Given Date.(Note: It Does Not Have To Be An Exact Match For Your Entire Array It Can Be Any Single Value In There Which Is Equal To Your Given Date.(Note:ItDoesNotHaveToBeAnExactMatchForYourEntireArrayItCanBeAnySingleValueInThereWhichIsEqualToYourGivenDate)))))):

        result = []

        for obj in queryset :

            result += [obj]

        return result

MyModel.objects.filter(my_dates__contains=date) # 작동하지 않습니다!

MyModel.objects.extra(select={'my_dates': "SELECT * FROM my_dates WHERE my_dates = %s"}, select_params=(date,))

어레이 작업

Django에서 배열은 단일 변수에 여러 값을 저장하는 편리한 방법입니다. 배열은 일반 Python 목록과 동일한 방식으로 인덱싱 및 액세스할 수 있으므로 중소 규모 응용 프로그램에 이상적인 데이터 구조가 됩니다.

Django에서 배열을 만들려면 array() 함수를 사용하십시오.

my_array = 배열(1, 2, 3)

배열의 개별 요소에 액세스하려면 index() 함수를 사용하십시오.

인쇄(my_array[0])
인쇄 1 . 배열의 요소를 반복하려면 for 루프를 사용하십시오.

my_array의 i에 대해: print(i)

일 위트 날짜

Django에서는 work_with() 함수를 사용하여 날짜를 관리할 수 있습니다. 이 함수는 날짜 개체와 작업 개체라는 두 가지 인수를 사용합니다. 날짜 개체는 작업이 시작되어야 하는 날짜를 나타내고 작업 개체는 해당 날짜에 수행하려는 작업을 나타냅니다.

예를 들어 work_with()를 사용하여 내일의 작업을 만들 수 있습니다.

work_with(date('내일'), task('새 블로그 게시물 만들기') )

Django의 배열

Django의 배열은 객체의 모음입니다. 배열은 0부터 시작하여 인덱싱되므로 0개의 요소가 있는 배열은 1, 2, 3, 4, XNUMX로 인덱싱됩니다.

배열의 첫 번째 요소에 액세스하려면 인덱스 0을 사용합니다. 배열의 마지막 요소에 액세스하려면 인덱스(n-1)를 사용합니다. 배열의 다른 요소에 액세스하려면 인덱스 n을 사용하십시오.

관련 게시물:

코멘트 남김