Django insert into list if doesn't contain it - python

I want to insert into the notifications list, one notification of each type. and I have this:
Result from the initial query (I guess is a list with queryset), named notifications:
[<Notification: Should be first>, <Notification: New link>]
And the restriction that I have is:
for(note in notification):
if len(note.region.all()) == 0 and (note.notificationType.priority not in notifications):
notifications.append(note)
My question is, how do I get inside the notifications list to get the attribute notificationType.priority to see is that number isn't inside notifications list.

If I get your question, you can try this :
notificationsPiorities = set([note.notificationType.priority for note in notifications ])
for(note in notification):
if len(note.region.all()) == 0 and (note.notificationType.priority not in notificationsPiorities ):
notifications.append(note)
notificationsPiorities.add(note.notificationType.priority)
Also, you may need to rename your variables. I can't tell for sure what are notification and notifications. One is the list you will display, and one is the list you retrieve with your query ?

Related

How do I make a top in discord.py using repl.it database

So basically I have some db keys (I use the XP prefix and the user's Id's: db["XP{user.id}"]). Each key contains an integer which is the XP earned in the server.
How do I make a list out of the keys and sort the list? (like a XP top)
The final output should look like:
1# Denis#1627 : 5382XP
2# Discord#5262 : 5000XP
also I'm sorry about any mistake, I'm new on stackoverflow
2 options:
The db.keys() function will return a set (like an array but it's unordered, iterable and have not duplicate items) with all the keys that you have stored in replit database.
For example:
database_keys = db.keys()
print(database_keys)
Expected output:
{'XP0000', 'XP1111', 'XP2222', 'server_name', 'server_admin', 'etc'}
If you store other keys that aren't storing the XP of users, and only want get the ones with XP prefix, you could use db.prefix(prefix) that recieves a prefix has a parameter. And it's going to return a tuple with all keys that start with the prefix. (The prefix must be an string)
For example:
XP_database_keys = db.prefix("XP") # will return all the database keys that start with "XP"
print(XP_database_keys)
Expected output:
('XP0000', 'XP1111', 'XP2222')
After getting the keys with any of the methods, you could with the same key get the user's id with discord.py, then getting their values "amount of XP" and then order from smallest to largest value and send it in a discord embed to your server.
Hope I've been helpful, have a nice day!

Python list.append not working. I'm using discord.py and replit database to make a gambling bot and I wanted a list of participants

So basically I'm trying to get a discord betting bot to give a list of participants that it can cycle through when games end. The problem is that when I use this code it doesn't seem to append. I've tried debugging it using an alt. The not in db['list'] part triggers fine, and there are no errors raised, but the list still only contains my main account's ID (which was used to create the list.)
The repl.it database is basically a big array with string indexes / keys. I'm sure that lists are an accepted data type since when I debugged before it printed db['list'] as ['#MYIDNUMBER'] but it still won't append my alt's.
db['list'] = [str(message.author.id)]
db['betenable'] = True
if message.content.startswith('$createaccount'):
db[str(message.author.id)+'wallet'] = 1000
db[str(message.author.id)+'ingame'] = 0
db[str(message.author.id)+'bet'] = 'No Party'
if str(message.author.id) not in db['list']:
db['list'].append(str(message.author.id))```
You're accessing db[list], using the list built-in, instead of the string, db['list'].

Make directory system from user id in python list

Please help!
Well, first of all, I will explain what this should do. I'm trying to store users and servers from discord in a list (users that use the bot and servers in which the bot is in) with the id.
for example:
class User(object):
name = ""
uid = 0
Now, all discord id are very long and I want to store lots of users and servers in my list (one list for each one) but suppose that I get 10.000 users in my list, and I want to get the last one (without knowing it's the last one), this would take a lot of time. Instead, I thought that I could make a directory system for storing users in the list and finding it quickly. This is how it works:
I can get the id easily so imagine my id is 12345.
Now I convert it into a string using python str(id) function and I store it in a variable, strId.
For each digit of the list, I use it as an index for the users list, like this:
The User() is where the user is stored
users_list = [[[], [[], [], [[], [], [], [User()]]]]]
actual_dir = 0
for digit in strId:
actual_dir = digit
user = actual_dir[0]
And that's how I reach the user (or something like that)
Now, here is where my problem is. I know I can get the user easily by getting the user by id, but when I want to save the changes, I should do something like users_list[1][2][3][4][5] = changed_user_variable, but how far I know I cannot do something like list[1] += [2]
Is there any way to reach the user and save the changes?
Thanks in advance
You can use a python dictionary with the user id as the key and the user object as the value. I ran a test on my own computer and found that finding 100 000 random users in a dictionary with 10 million users only took 0.3s. This method is much simpler and I would guess it's just as fast, if not faster.
You can create a dictionary and add users with:
users = {}
users[userID] = some_user
(many other ways of doing this)
by using a dictionary you can easily change a user's field by:
users[userID].some_field = "Some value"
or overwrite the same way you add users in the first place.

how to remove an item from django session?

I do have two items in request.session.get('product_key'). I am trying to delete one product.
m = request.session['product_key']
m.remove('768')
when i am trying to delete one product from the session its getting deleted from the variable but not from actual session. when i am printing m its giving me single product while i am typing request.session.get('product_key') its giving me two products.
So, how can i achieve so?
Edit:
I dont want to delete complete session, i want to delete one variable from the session,i have 2 items in one key name.
print(request.session['product_key']) = ['123','768']
If you modify a list in a session value - rather than changing or replacing the value completely - Django will not automatically know it needs to save the session. You need to tell it explicitly:
request.session.modified = True
See the docs on When sessions are saved.
try :
del request.session['your key']
or
m = request.session.pop('your key')
Here you go;
request.session["your key"].pop(index of the element you want to remove)
request.session.modified = True

Google Directory API groups

I am trying to use Google's admin directory API (with Google's python library).
I am able to list the users on the directory just fine, using some code like this:
results = client.users().list(customer='my_customer').execute()
However, those results do not include which groups the users are a member of. Instead, it appears that once I have the list of users, I then have to make a call to get a list of groups:
results = client.groups().list(customer='my_customer').execute()
And then go through each group and call the "members" api to see which users are in a group:
results = client.members().list(groupKey='[group key]').execute()
Which means that I have to make a new request for every group.
It seems to be horribly inefficient. There has to be a better way than this, and I'm just missing it. What is it?
There is no better way than the one you described (yet?): Iterate over groups and get member list of each one.
I agree that is not the answer you want to read, but it is also the way we do maintenance over group members.
The following method should be more efficient, although not 100% great :
For each user, call the groups.list method and pass the userKey parameter to specify that you only want groups who have user X as a member.
I'm not a Python developper, but it should look like this :
results = client.groups().list(customer='my_customer',userKey='user#domain.com').execute()
For each user:
results = client.groups().list(userKey=user,pageToken=None).execute()
where 'user' is the user's primary/alias email address or ID
This will return a page of groups the user is a member of, see:
https://developers.google.com/admin-sdk/directory/v1/reference/groups/list

Categories

Resources