0

Please can you check my python code below if it okay to do this for a queryset :

gp_id= [0,1,2]
for gp in gp_id:
    specail_list = Special.objects.filter(
        promotion=False, 
        start__lte=date_instance, 
        minimum_stay__lte=nights, 
        object_id=room_filter.id, 
        end__gte=date_instance, 
        is_active=True, 
        member_deal=False
    )[gp]
    print specail_list
3
  • What are you trying to do with the queryset? Commented Dec 4, 2018 at 5:09
  • i am trying to get what is returned if add 0 on the [] or 1 or 2 Commented Dec 4, 2018 at 5:12
  • Still not clear what is the aim of this code. Commented Dec 4, 2018 at 5:38

2 Answers 2

1

So I think you are trying to ask for the first three elements in the list, indexes 0, 1, 2. So while what you are doing is valid, this way is better.

Slice - common function each python programmer should know:

Python Docs for "Slice: https://docs.python.org/3/library/functions.html#slice

Django Docs for "Limiting Querysets": https://docs.djangoproject.com/en/2.1/topics/db/queries/#limiting-querysets

Will grab first three elements starting on the not entered 0th index. The brackets could have also been [0:3].

special_list = Special.objects.filter(
    promotion=False, 
    start__lte=date_instance, 
    minimum_stay__lte=nights, 
    object_id=room_filter.id, 
    end__gte=date_instance, 
    is_active=True, 
    member_deal=False
)[:3]
Sign up to request clarification or add additional context in comments.

2 Comments

thanks yes i have already tried that but it did not work on my entire code
Maybe edit your question to show examples of where it didn't work.
0

I think you can loop though like this:

special_queryset = Special.objects.filter(
    promotion=False, 
    start__lte=date_instance, 
    minimum_stay__lte=nights, 
    object_id=room_filter.id, 
    end__gte=date_instance, 
    is_active=True, 
    member_deal=False
    id__in = gp_id
)
for i in special_queryset:
    print(i)

If you want to update the same thing for the items in the queryset, then use update() method.

special_queryset.update(promotion=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.