why django multivaluedict get returns last element - python

I have used Django MultiValueDict many times and all the times either I use the entire list stored with a key or I want to use the first value from the list. A common use case is use it as form initial data.
My problem is that by default Django MultiValueDict's get method returns last element.
Do I have to override getitem of MultiValueDict or is there any better alternative ?

You can use:
mv_dict.getlist()[index]
Where index is the index of the element you want in the list. For example 0 to get the first element.
Check https://github.com/django/django/blob/master/django/utils/datastructures.py#L285
But certainly if for some reason you always want to return the first element of the list, subclassing MultiValueDict sounds reasonable. It depends on your use case.

Related

Understanding selenium web-elements list

Ok so I had a list of web items created by seleniums Webdriver.find_elements_by_path method, and I had trouble utilizing the data.
Ultimately, the code I needed to get what I wanted was this:
menu_items=driver.find_elements_by_xpath('//div[#role="menuitem"]')[-2]
I was only ever able to get any meaningful data here by using a negative index. If I used any positive indices, the menu_items would return nothing.
However, when I had left menu_items as follows:
menu_items=driver.find_elements_by_xpath('//div[#role="menuitem"]')
I could iterate through the list and gain access to the webelements properly, meaning if I had"for i in menu_items" I could call something like i.text and have the desired result. But again, I could not do menu_items[2]. I am new to selenium so if someone could explain what is going on here, that would be very helpful
This line of code...
menu_items=driver.find_elements_by_xpath('//div[#role="menuitem"]')[-2]
...indicates you are considering the second element counting from the right instead of the left as list[-1] refers to the last element within the list and list[-2] refers to the second last element in the list.
A bit more about your usecase would have helped us to construct a canonical answer. The number of visible/interactable elements at any given point of time and/or the sequence in which the elements gets visible/interactable may vary based on the type of elements present in the DOM Tree. Incase the HTML DOM consists of JavaScript, Angular, ReactJS, enabled elements even the position of the elements may differ as well.

How to delete first N items from queryset in django

I'm looking to delete only the first N results returned from a query in django. Following the django examples here which I found while reading this SO answer, I was able to limit the resulting set using the following code
m = Model.objects.all()[:N]
but attempting to delete it generates the following error
m.delete()
AssertionError: Cannot use 'limit' or 'offset' with delete.
Is there a way to accomplish this in django?
You can not delete through a limit. Most databases do not support this.
You can however accomplish this in two steps, like:
Model.objects.filter(id__in=list(Models.objects.values_list('pk', flat=True)[:N])).delete()
We thus first retrieve the primary keys of the first N elements, and then use this in a .filter(..) part to delete those items in bulk.
You don't have the option directly. So you should delete it by some advanced ways. For example:
not_ideal = Model.objects.all()[N:].values_list("id", flat=True)
Model.objects.exclude(pk__in=list(not_ideal)).delete()
Using this way you are finding your not ideal objects and delete everything except them.
You can use anything beside id. But id is unique and will help you to optimize.
Notice that in the first line I'm getting the items which are from N to the last.(Not from the first to N)
Try this.
Loop through all filtered objects
delatable_objects = Model.objects.all()[:N]
for m in delatable_objects:
m.delete()
You can loop through the queryset and apply delete method to the objects.
for obj in m:
obj.delete()

Check an object in a list of values

First, I would like to mention I am to automated testing.
I want to add a test case to Robot Framework which will let me choose from a list (which can change).
I have problem with creating keywords to do this.
Can somebody give me a tips to do this?
I have a list, but the values can change. I need to check values inside the list the list.
There is a value in the list that I would like to change.
Edit: The questions applies the list on web page.
In your test case you'll need to import the library Collections.
To check a value in a list you can use the keyword
list should contain value #{MyList} Value
If you want to set a value in the list to something else you can use the keyword
set list value #{MyList} 1 Value
If you want to learn more about these keywords you can find them here.
http://robotframework.org/robotframework/latest/libraries/Collections.html

Assign many values to an element of a list

If I want to assign to an element of a list only one value I use always a dictionary. For example:
{'Monday':1, 'Tuesday':2,...'Friday':5,..}
But I want to assign to one element of a list many values, like for example:
Monday: Jogging, Swimming, Skating
Tuesday: School, Work, Dinner, Cinema
...
Friday: Doctor
Is any built-in structure or a simple way to make something like this in python?
My idea: I was thinking about something like: a dictionary which as a key holds a day and as a value holds a list, but maybe there is a better solution.
A dictionary whose values are lists is perfectly fine, and in fact very common.
In fact, you might want to consider an extension to that: a collections.defaultdict(list). This will create a new empty list the first time you access any key, so you can write code like this:
d[day].append(activity)
… instead of this:
if not day in d:
d[day] = []
d[day].append(activity)
The down-side of a defaultdict is that you no longer have a way to detect that a key is missing in your lookup code, because it will automatically create a new one. If that matters, use a regular dict together with the setdefault method:
d.setdefault(day, []).append(activity)
You could wrap either of these solutions up in a "MultiDict" class that encapsulates the fact that it's a dictionary of lists, but the dictionary-of-lists idea is such a common idiom that it really isn't necessary to hide it.

Referring to objects inside a list without using references or indices

I'm using python for my shopping cart class which has a list of items. When a customer wants to edit an item, I need to pass the JavaScript front-end some way to refer to the item so that it can call AJAX methods to manipulate it.
Basically, I need a simple way to point to a particular item that isn't its index, and isn't a reference to the object itself.
I can't use an index, because another item in the list might be added or removed while the identifier is "held" by the front end. If I were to pass the index forward, if an item got deleted from the list then that index wouldn't point to the right object.
One solution seems to be to use UUIDs, but that seems particularly heavyweight for a very small list. What's the simplest/best way to do this?
Instead of using a list, why not use a dictionary and use small integers as the keys? Adding and removing items from the dictionary will not change the indices into the dictionary. You will want to keep one value in the dictionary that lets you know what the next assigned index will be.
A UUID seems perfect for this. Why don't you want to do that?
Do the items have any sort of product_id? Can the shopping cart have more than one of the same product_id, or does it store a quantity? What I'm getting at is: If product_id's in the cart are unique, you can just use that.

Categories