Im trying to do a simple check if there is 3 specific value in a string. If there is, the statement should return nothing, instead of save.
Here is my code, but I think the syntax is wrong:
if not ('2239687' or '2238484' or '2239440') in user_id:
#The user is not admin, save the user
web_user.save()
To elaborate, I want it to test if user_id is "2239687" or "2238484" or "2239440" (and not, for example, "002239440"). If the user_id is one of those three values (and ONLY those three values), the statement should return false.
if not any(x in user_id for x in ('2239687', '2238484', '2239440')):
#The user is not admin, save the user
web_user.save()
This checks whether none of the three string is present within user_id.
One more option:
if not any(idx in user_id for idx in ('2239687' ,'2238484' , '2239440')):
# do something
Try like this
if user_id not in ('2239687' ,'2238484' , '2239440'):
Or
if not user_id in ('2239687' ,'2238484' , '2239440'):
Related
I am trying to insert the API query response in to the SQL server database. On a particular field I need to check if the value of the field on the Query response is true or false , if it is false I need to insert 'F' if its true I need to insert 'T' a field in DB
cursor = sqlconn.cursor()
for index,row in roomsDF.iterrows():
cursor.execute("INSERT INTO SurplusMouse.RM_Room(ROOMID, NAME, DESCRIPTION, SHIPPING_FREEZE, UPDATEDNAME)\
values(?,?,?,?,?)"
,row['id']
,row['name']
,row['description']
, if row['shippingFreeze'] == false:
'F'
else:
'T'
,row['shippingFreeze'].split(' ', 1)
)
I see two errors here one on the cursor.execute(" as "(" was not closed and another issue is Expected expression Pylance erroron the if . This is my first Python script and not sure if I am missing something any help is greatly appreciated
It seems to me you are mixing two different concepts. You need to divide and conquer.
Retrieve the data, and create a variable for each value.
id = row['id']
name = row['name']
shippingFreeze = 'T' if row['shippingFreeze'] else 'F'
Then, create the execute command. Make sure that the shippingFreeze attribute comes correctly formatted as boolean.
Regards
L.
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 a simple function which should update a certain column for certain users:
for key, group in groupby(list_i):
print key, type(key), len(list(group)), type(len(list(group)))
setattr(User.query.filter_by(id=key).first(), "number_of_rooms", len(list(group)))
db_session.commit()
I have a list (list_i) which has the data, simply look at the print:
The data is correct, the first number is the id of the user and the second is the value which should be assign to column number_of_rooms
The problem is it sets all values of the users to 0. I assume it is somehow an override issue of the last user, I dont know. The thing is if I change it to:
setattr(User.query.filter_by(id=key).first(), "number_of_rooms", 2)
It will change the value to 2 for all users with id=key so the function works. I am here very confused, because len(list(group)) is a simple integer and it should work.
EDIT:
I double checked everything, I also made an other test with a variable (t) which increments by 1 and added an onther print to check everything, with the variable it also works, how is that possible?
t = 0
for key, group in groupby(list_i):
print key, type(key), len(list(group)), type(len(list(group)))
my_user = User.query.filter_by(id=key).first()
setattr(my_user, "number_of_rooms", t)
print my_user.number_of_rooms
t+=1
db_session.commit()
The value of number_of_rooms changes:
As Roman Mindlin and glibdud have specified, list(group) can only be used once. Since group is of type <type 'itertools._grouper'>, after you iterate over group once (e.g. by calling list() on it), it's exhausted. The key is to save the list(group) inside a variable.
Here is the code that fixes the issue:
for key, group in groupby(list_i):
l_group = list(group)
print(l_group)
my_user = User.query.filter_by(id=key).first()
setattr(my_user, "number_of_rooms", len(l_group))
db_session.commit()
I'am trying to create a model unittest for a ManyToMany relationship.
The aim is to check, if there is the right category saved in the table Ingredient.
class IngredientModelTest(TestCase):
def test_db_saves_ingredient_with_category(self):
category_one = IngredientsCategory.objects.create(name='Food')
first_Ingredient = Ingredient.objects.create(name='Apple')
first_Ingredient.categories.add(category_one)
category_two = IngredientsCategory.objects.create(name='Medicine')
second_Ingredient = Ingredient.objects.create(name='Antibiotics')
second_Ingredient.categories.add(category_two)
first_ = Ingredient.objects.first()
self.assertEqual('Apple', first_.name)
self.assertEqual(first_.categories.all(), [category_one])
self.assertEqual(first_, first_Ingredient)
for self.asserEqual(first_.categories.all(), [category_one]) in the second last row I get this weird assert:
AssertionError: [<IngredientsCategory: Food>] != [<IngredientsCategory: Food>]
I tried many other different ways, but none of it worked. Does any one suppose how I can get the information of first_.categories.all() to compare it with something else?
That'll be because they're not equal - one is a QuerySet, the other is a list - they just happen to have the same str representations.
You could either cast the QuerySet to a list with list(first_.categories.all()), or a possible solution for this situation may be:
self.assertEqual(first_.categories.get(), category_one)
I am having difficulties with accessing an instance within a structured list.
Below is my structured list:
class FavFruits(ndb.Model):
fruit = ndb.StringProperty()
score = ndb.IntegerProperty()
comment = ndb.TextProperty()
class UserProfile(ndb.Model):
uid = ndb.StringProperty(required=True)
password = ndb.StringProperty(required=True)
firstName = ndb.StringProperty(required=True)
favFruits = ndb.StructuredProperty(FavFruits, repeated=True)
I want to display score under FavFruits entity.
I tried UserProfile.favFruits.score with no luck.
I also tried UserProfile.favFruits[index].score, which worked, but now requires looping and I would like to avoid it.
Ultimately, I want to do the following logic:
if UserProfile.uid == userEntering then user enters fruit name
if UserProfile.favFruits.fruit == fruitName (user entered) then display UserProfile.favFruits.score and UserProfile.favFruits.comments for UserProfile.favFruits.fruit specified by user.
Lastly, I would like to display all the fruit/scores that user enters. Say, user entered "apple" and "orange" for fruit names, then I want to loop, for example (along this line):
for x in fruitNames
print x
print UserProfile.favFruits.score.query(UserProfile.favFruits.fruit == x)
Is this possible? Seemingly trivial task, but I cannot figure this out..
Thank you in advance!
Your requirements are contradictory. If you don't want to loop, then don't use repeated=True. But then you won't be able to store more than one for each entity. There's no possible way to have multiple things without looping or indexing.