I have looked at the questions on here and none of them seem to help my cause. Essentially what I am doing is calling getAllOpenChoices to try and return a the value of the Radio button so when one is selected it saves.
forms.py
def getAllOpenChoices():
listOpenChoice = [('All', 'All'), ('No One', 'No One'), ('Test','Test')]
all_choices = Requisition.objects.distinct()
for choices in all_choices:
temp = (Requisition.objects.filter(open_to=choices))
listOpenChoice.append(temp)
return tuple(listOpenChoice)
This error that I am getting is:
ValueError: need more than 0 values to unpack
getAllOpenChoices is being called:
self.fields['open_to'] = forms.ChoiceField( choices = getAllOpenChoices, widget = forms.RadioSelect())
The choices should be a list of 2-tuples, like your initial value listOpenChoice
listOpenChoice = [('All', 'All'), ('No One', 'No One'), ('Test','Test')]`
If you extend that list, you should only add 2-tuples. For example:
listOpenChoice.append(('new', 'New'))
However, you are appending querysets, e.g. Requisition.objects.filter(open_to=choices). This doesn't make sense. One of your querysets is empty, which is why you get the zero in the error message "need more than 0 values to unpack".
It's not clear to me what you're trying to append to the list, so I can't tell you how to fix your code. As long as you only append 2-tuples, you should be ok.
Related
Here is the example I am referring to:
all_hats = Hats.objects.all()
issues=[]
issues_to_match = [issue.id for issue in issues]
matching_issues_count = Count("issues", filter=Q(issues__id__in=issues_to_match))
qs = all_hats.annotate(matching_issues_count=matching_issues_count)
qs.filter(matching_issues_count=0)
So if in this case issues is an empty list, when you print qs.matching_issues_count you get 0. So when you qs.filter(matching_issues_count=0) you should get that result no?
In reality you return an empty queryset.
Furthermore, print(qs.filter(matching_issues_count=0).query) returns an EmptyResultSet ValidationError
Any information on this or do I have to structure the query another way? Or add a condition for when issues is empty? Thanks.
I have the following code which creates a list, takes inputs of column names the user wants, then a for loop applies each list attribute individually to check in the if statement if the user input matches the columns in the data frame.
Currently this produces an exception handling statement if all inputs to the list are unmatching, but if item in the list matches the column in the dataframe but others do not, then jupyter will produce its own error message "KeyError: "['testcolumnname'] not in index", because it is trying to move onto the else part of my statement and create the new dataframe with this but it cant (because those columns do not exist)
I want it to be able to produce this error message 'Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.' if even 1 inputted list attribute does not match the dataframe and all other do. But Ive been struggling to get it to do that, and it produces this KeyError instead.
My code:
lst = []
lst = [item for item in str(input("Enter your attributes here: ")).lower().split()]
for i in lst:
if i not in df.columns:
print('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.')
break
else:
df_new = df[lst]
# do other stuff
for example if i have a dataframe:
A
B
C
NA
yes
yes
yes
no
yes
and my list contains:
['A','B','C']
It works correctly, and follows the else statement, because all list items match the dataframes columns so it has no problem.
Or if it has this:
['x','y','z']
It will give the error message I have, correctly. Because no items match the data frames items so it doesn't continue.
But if it is like this, where one attribute is matching the dataframe, and others not...
['A','D','EE']
it gives the jupyter KeyError message but I want it to bring back the print message i created ('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.').
The KeyError appears on the line of my else statement: 'df_new = df[lst]'
Can anyone spot an issue i have here that will stop it from going this? Thank you all
Try not to print, but to raise exception
And you need to fix your indentation
lst = []
lst = [item for item in str(input("Enter your attributes here: ")).lower().split()]
for i in lst:
if i not in df.columns:
raise ValueError('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.')
df_new = df[lst]
# do other stuff
So basically atm i've made two different lists, and their places are respective of each other.
User inputs an item name. The program searches for its index in the pre-defined list and then gives its respective value from the second list.
What i want is the list on the first comment (2d list) to work. Is it possible that using that list, a user inputs : 'Bread'.
The program gets its index and then returns the value 5.
Basically indexing in 2d list.I've searched a lot but to no avail.
If you could provide a code or atleast guide me the right way.
Thanks.
#super_market_prices=[['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]
'''
Program listing Super Market Prices
Search by name and get the price
'''
super_market_items=['Bread','Loaf','Meat_Chicken','Meat_Cow']
super_market_prices=[5,4,20,40]
item=str(input('Enter item name: '))
Final_item=item.capitalize() #Even if the user inputs lower_case
#the program Capitalizes first letter
try:
Place=super_market_items.index(Final_item)
print(super_market_prices[Place])
except ValueError:
print('Item not in list.')
You don't want a 2D list, you want a dictionary, and luckily, it's super simple to go from a 2D list (where each sublist has only two elements) to a dictionary:
prices = [['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]
d = dict(prices)
# {'Bread': 5, 'Loaf': 100, 'Meat_Chicken': 2.4, 'Meat_Cow': 450}
Now all you have to do is query the dictionary (O(1) lookup):
>>> d['Bread']
5
If you want to enable error checking:
>>> d.get('Bread', 'Item not found')
5
>>> d.get('Toast', 'Item not found')
'Item not found'
You can easily go from your "2d-list" from those two separate sequences by using zip
super_market_prices=[['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]
l1, l2 = zip(*super_market_prices)
>>> print(l1)
('Bread', 'Loaf', 'Meat_Chicken', 'Meat_Cow')
>>> print(l2)
(5, 100, 2.4, 450)
and just keep your code as is.
This is another work around to your problem. P.S: I used #user3483203's suggestion to use item.title() instead of item.capitalize() as the latter was resulting in error for the string with an underscore. Here I am making use of the fact that each item is succeeded by its price. Hence index+1
super_market_prices=np.array([['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]).ravel()
item=str(input('Enter item name: '))
Final_item=item.title()
try:
index = np.where(super_market_prices == Final_item)[0]
print (float(super_market_prices[index+1][0]))
except ValueError:
print('Item not in list.')
I'm looking to do something like this:
u = User.objects.filter(name__isnull=True)[0]
The default value in MySQL for name is None. I also tried:
u = User.objects.filter(name=None)[0]
Neither have returned anything, aka, IndexError: list index out of range. How do I get an object with no value set as the name?
Even thought MySQL says the default value is None, Django used "" as the default, so I used:
User.objects.filter(name="").first()
You are missing some key concepts.
IndexError: list index out of range
This error is not a error looking in the db, this error is given because you are trying to do something with an index of array which does not exist.
a = [1,2,3]
a[0] = 1
a[2] = 2
a[3] = 3
a[4] = IndexError: list index out of range
a[n] = IndexError: list index out of range
you can do normaly:
u = User.objects.filter(name=None)
In the DB if you set Null = True and blank = True (i don't recommend this) in the models you can have 'name=None' and 'name=""'
The problem is you are supposing it must be at least one User with your params, for that you are adding the [0] to retrieve a user instance instead a queryset.
If you expect to retrieve only and only one item of the query you must use the .get, (normally used searching pk, if more than one item is returned it gives an error)
u = User.objects.get(name=None)
but, if you know more than one item can exist in your with the filters, (for instance, the name not the pk) and you only care about the first you use the .first method, and later you check if exist.
User.objects.filter(name="").first()
I have a ManyToManyField in my model. I need to get the third item for every query as below.
class Staff(models.Model):
status = models.BooleanField(default=True)
person = models.ForeignKey(Person)
staff_job_categories = models.ManyToManyField(StaffJobCategory)
staff_titles = models.ManyToManyField(PersonTitle, null=True, blank=True)
def get_job_categories(self):
return self.staff_job_categories.all()[3]
I use the get_job_categories function for admin list_filter but I want to show only the 3rd item in every many to many array.
But get the
List index out of range ERROR;
by the way;
def get_job_categories(self):
return self.staff_job_categories.all()[:3]
Works fine. but gets all the objects till i get what i want.
This should work for jobs binded to less than 3 categories:
return ( self.staff_job_categories.all()[2]
if self.staff_job_categories.count() >= 3
else None
)
Or:
return ( self.staff_job_categories.all()[2]
if len( self.staff_job_categories.all()[:3] ) >= 3
else None
)
To avoid all categories recount.
The first item in a sequence has index 0. The third item has index 2. Perhaps that's your only problem?
E.g. try:
def get_job_categories(self):
return self.staff_job_categories.all()[2]
However, this assumes that you know for certain that all staff have at least three job categories and that their order is predictable. Is that actually the case? I don't think Django's ManyToManyField gives you any guarantee about the order that the related objects will be returned.