I have these following two data which I want to save into session, so that I can call all of them in last-preview page:
1) product title, 2) product size
I am wondering how to save this into session. My problems are: Session keys are unique so I cannot name the session name with some name. another issue is that these 2 data are coming dynamically. So I cannot use the product title as session key.
I want that both data is saved in one session variable.
Session variables are simply stored as the json-serialization of the actual value. This means that you can use lists, tuples and dictionaries, and any other json-serializable values.
One solution is to store your products as a list of (name, size) tuples. Then you can do:
if request.session['products']:
request.session['products'].append(('name', size))
else:
request.session['products'] = [('name', size)]
Related
When I try to save a new item I need to find the item with the highest ID in the database in order to add 1 to it and save the next item in the order in the database. Simply counting the items in the DB will not work as if an item is deleted the count will be incorrect.
I have no code to fix but pseudo looks something like:
look at all the items in the DB
Find the item with the highest ID
Add one to that number
save the new item with the new highest id in the DB
I am using Django. as such it should use the querysets within Django and or python.
Field id of the Django Model is by default auto increment so whenever you save a new object to the database it does exactly what you want - saves object with id greater than the last object's id by one.
Anyways, there are multiple ways you can retrieve latest id from the database.
The most efficient way (simplest and fastest database query since you want only id value returned, not the whole object) is by saying:
latest_id = Model.objects.all().values_list('id', flat=True).order_by('-id').first()
The queryset looks like this:
SELECT 'model'.'id' FROM 'model' ORDER BY 'model'.'id' DESC LIMIT 1;
all() gets all objects of the model from the database, values_list('id', flat=True) extracts only the value of the id field (this saves you time because you don't retrieve all model fields), order_by('-id') orders objects by id in descending order and first() gives you the desired result which is the last id.
There is also method like last() that does the oposite of method first(). It retrieves last whole object of the model from the database or the method latest('id') which does the same.
I'm wanting to pass information relating to orders into my template via an ajax call. The problem is that that I've got more than two values that I want to pass in.
Key: Email address
Values that pertain to each key that I want to pass in:
Invoice Date
Name
Phone number
I'm wondering what the best way to do this is. Does the dictionary value need to be a list?
eg.
order_dict[order.email] = ['order.invoice_date', 'order.name', 'order.phone']
If the dictionary value does need to be a list, how would I iterate over it in my template?
Thanks for your help!
deliveryMethod = SelectField('Delivery method/Channel', choices = [(1, 'Accounts opened with adequate CDD measures carried out'),(1,'Delivery channels linked with accounts opened with adequate CDD measures carried out'),(2, 'Product serviced by agents'),(2,'Certificate of Deposit'),(4,'Non face-to-face customers'),(4,'Mobile/Internet banking facilities not linked with accounts'),(4,'Products served with unregistered beneficiaries')])
in hear choices have multiple same key.i want get non key values from this,how can get this non key value ?
Choices is a list of tuples. If you just want the "values", try this:
values = [x[-1] for x in form.deliveryMethod.choices]
I show a model of sales that can be aggregated by different fields through a form. Products, clients, categories, etc.
view_by_choice = filter_opts.cleaned_data["view_by_choice"]
sales = sales.values(view_by_choice).annotate(........).order_by(......)
In the same form I have a string input where the user can filter the results. By "product code" for example.
input_code = filter_opts.cleaned_data["filter_code"]
sales = sales.filter(prod_code__icontains=input_code)
What I want to do is filter the queryset "sales" by the input_code, defining the field dynamically from the view_by_choice variable.
Something like:
sales = sales.filter(VARIABLE__icontains=input_code)
Is it possible to do this? Thanks in advance.
You can make use of dictionary unpacking [PEP-448] here:
sales = sales.filter(
**{'{}__icontains'.format(view_by_choice): input_code}
)
Given that view_by_choice for example contains 'foo', we thus first make a dictionary { 'foo__icontains': input_code }, and then we unpack that as named parameter with the two consecutive asterisks (**).
That being said, I strongly advice you to do some validation on the view_by_choice: ensure that the number of valid options is limited. Otherwise a user might inject malicious field names, lookups, etc. to exploit data from your database that should remain hidden.
For example if you model has a ForeignKey named owner to the User model, he/she could use owner__email, and thus start trying to find out what emails are in the database by generating a large number of queries and each time looking what values that query returned.
Can anyone help, I want to return an ordered list based on forloop in Django using a field in the model that contains both integer and string in the format MM/1234. The loop should return the values with the least interger(1234) in ascending order in the html template.
Ideally you want to change the model to have two fields, one integer and one string, so you can code a queryset with ordering based on the integer one. You can then define a property of the model to return the self.MM+"/"+str( self.nn) composite value if you often need to use that. But if it's somebody else's database schema, this may not be an option.
In which case you'll have to convert your queryset into a list (which reads all the data rows at once) and then sort the list in Python rather than in the database. You can run out of memory or bring your server to its knees if the list contains millions of objects. count=qs.count() is a DB operation that won't.
qs = Foo.objects.filter( your_selection_criteria)
# you might want to count this before the next step, and chicken out if too many
# also this simple key function will crash if there's ever no "/" in that_field
all_obj = sorted( list( qs),
key = lambda obj: obj.that_field.split('/')[1] )