Nalutas: django array ng mga petsa

Ang pangunahing problema sa mga arrays ng mga petsa ay maaaring mahirap gamitin ang mga ito. Ang mga array ng mga petsa ay mga koleksyon lamang ng mga petsa, at dahil dito ay maaaring mahirap manipulahin.

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) # ay hindi gumagana!

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

Makipagtulungan sa Arrays

Sa Django, ang mga array ay isang maginhawang paraan upang mag-imbak ng maramihang mga halaga sa iisang variable. Ang mga array ay maaaring ma-index at ma-access sa parehong paraan tulad ng mga regular na listahan ng Python, na ginagawa itong isang perpektong istraktura ng data para sa mga maliliit hanggang katamtamang laki ng mga application.

Upang lumikha ng array sa Django, gamitin ang array() function:

my_array = array(1, 2, 3)

Upang ma-access ang mga indibidwal na elemento ng isang array, gamitin ang index() function:

print(my_array[0])
mga kopya 1. Upang umulit sa mga elemento ng isang array, gamitin ang for loop:

para sa i sa my_array: print(i)

Magtrabaho sa mga petsa

Sa Django, maaari mong gamitin ang work_with() function upang pamahalaan ang mga petsa. Ang function na ito ay tumatagal ng dalawang argumento: isang date object at isang work object. Kinakatawan ng object ng petsa ang petsa kung kailan dapat magsimula ang trabaho, at kinakatawan ng object ng trabaho ang gawain na gusto mong gawin sa petsang iyon.

Halimbawa, maaari mong gamitin ang work_with() upang lumikha ng isang gawain para bukas:

work_with(date('bukas'), task('create new blog post') )

Mga array sa Django

Ang array sa Django ay isang koleksyon ng mga bagay. Ang mga array ay nai-index simula sa 0, kaya ang isang array na may limang elemento ay mai-index bilang 0, 1, 2, 3, 4.

Upang ma-access ang unang elemento sa isang array, gamitin ang index 0. Upang ma-access ang huling elemento sa isang array, gamitin ang index (n-1). Upang ma-access ang anumang iba pang elemento sa isang array, gamitin ang index n.

Kaugnay na mga post:

Mag-iwan ng komento