Poco HTMLForm multiple parameter with same key - c++

I'm using Poco::Net:HTMLForm to POST a request.
Now I want to put in the form:
form[key] = value1
form[key] = value2
And the server side can transform key to a list [value1, value2].
I can do this while test with Postman, but in POCO HTMLForm, value2 will overwrite value1.
Is there any way to implement this in Poco::Net::HTMLForm?

You can use
form.add(name, value);
to add multiple fields with the same name.

No, as you noticed - same keys will be overwritten. Assembling data yourself is not that complicated, though:
?key=value1&key=value2
Issue filed on github.
UPDATE: use form.add(name, value), it will allow multiple values.

Related

How to get and update Django object in one query?

To optimize a lot my database I would like to make as less as possible any query.
I'm trying to get an object, increment the field "count_limit" and make an If statement after on the Customer instance.
To achieve it I've made this query who worked well.
Customer.objects.filter(user=user).update(count_limit=F('count_limit') + 1)
So after this query, count_limit has been incremented by 1 as I wanted.
When I'm trying to get the Customer instance as a result of this query, it returns "1".
Is it possible to make both, update the instance and get it as a return object ?
Thanks a lot
The update() method will return the number of updated rows. If you are using Postgres, then you can use the returning clause with the raw query.
query = 'UPDATE customer SET count_limit=(customer.count_limit + 1) WHERE customer.user_id=%s returning *'
updated_obj = Customer.objects.raw(query, [user.id])
I don't know if this can be achieved by ORM, but suggestions will be appreciated.
Make sure that the table name in raw query is correct. If you haven't definer db_table in the meta class of your model, then by default it will be myapp_model.
And to prevent SQL injection, from the Docs:
Do not use string formatting on raw queries or quote placeholders in
your SQL strings!
Follow Docs on raw()
You are looking for F functions: https://docs.djangoproject.com/en/3.0/ref/models/expressions/#f-expressions
Example from their documentation how to increase a counter
from django.db.models import F
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()

Named queries in webservices

I want to retrieve all records with shelfId=1 and between two dates. I wrote a query like this in my webservice Its not working. can anyone please correct this one.
#NamedQuery(name = "BinEnvironment.BinEnvironmentByStartDateEndDate", query = "SELECT b FROM BinEnvironment b where shelfId ='?1' and dateTime between '1?' and '?2'")
Reply as soon as possible
Regards
Hema
There is a problem with your parameter declaration: you are trying to use the same param for shelfId and dateTime.
The declaration of parameters for the between case shoudl probably be between '?2' and '?3.
Please note the correct syntax (use ?1 instead of 1?):
Input parameters are designated by the question mark (?) prefix followed by an integer. For example: ?1.

django - get the id of just updated record

On my Django app I'm doing an update like this:
r = Mycords.objects.select_related().filter(name=r_name).update(title=r_title, message_body=r_message)
I need to get the id of just updated record so I can use it somewhere else on the code. Any ideas?
Whoah.
Firstly, if this is just a single record, you should use get rather than filter.
Secondly, what's select_related doing in there?
Thirdly, all the updated records are in r. So you can access their IDs from there.

Using a string as the argument to a Django filter query

I'm trying to do a django query, but with the possibility of several different WHERE parameters. So I was thinking of doing something like:
querystring = "subcat__id__in=[1,3,5]"
Listing.objects.filter(querystring)
Here Listing is defined in my model, and it contains the Many-To-Many field subcat. However, that raises a ValueError because filter doesn't accept a string as its argument. Is there a way in Python to have a string evaluated as just its contents rather than as a string? Something like a print statement that prints the value of the string inline rather than to the standard output.
By the way, the reason I don't just do
querystring = [1,3,5]
Listing.objects.filter(subcat__id__in=querystring)
is that I'm not always filtering for subcat__id, sometimes it's one or several other parameters, and I'd rather not have to write out a bunch of separate queries controlled by if statements. Any advice is much appreciated.
Perhaps...
filter_dict = {'subcat__id__in': [1,3,5]}
Listing.objects.filter(**filter_dict)
Listing.objects.filter(**{"subcat__id__in": ast.literal_eval("[1,3,5]")})

Get last record in a queryset

How can I retrieve the last record in a certain queryset?
Django Doc:
latest(field_name=None) returns the latest object in the table, by date, using the field_name provided as the date field.
This example returns the latest Entry in the table, according to the
pub_date field:
Entry.objects.latest('pub_date')
EDIT : You now have to use Entry.objects.latest('pub_date')
You could simply do something like this, using reverse():
queryset.reverse()[0]
Also, beware this warning from the Django documentation:
... note that reverse() should
generally only be called on a QuerySet
which has a defined ordering (e.g.,
when querying against a model which
defines a default ordering, or when
using order_by()). If no such ordering
is defined for a given QuerySet,
calling reverse() on it has no real
effect (the ordering was undefined
prior to calling reverse(), and will
remain undefined afterward).
The simplest way to do it is:
books.objects.all().last()
You also use this to get the first entry like so:
books.objects.all().first()
To get First object:
ModelName.objects.first()
To get last objects:
ModelName.objects.last()
You can use filter
ModelName.objects.filter(name='simple').first()
This works for me.
Django >= 1.6
Added QuerySet methods first() and last() which are convenience methods returning the first or last object matching the filters. Returns None if there are no objects matching.
When the queryset is already exhausted, you may do this to avoid another db hint -
last = queryset[len(queryset) - 1] if queryset else None
Don't use try...except....
Django doesn't throw IndexError in this case.
It throws AssertionError or ProgrammingError(when you run python with -O option)
You can use Model.objects.last() or Model.objects.first().
If no ordering is defined then the queryset is ordered based on the primary key. If you want ordering behaviour queryset then you can refer to the last two points.
If you are thinking to do this, Model.objects.all().last() to retrieve last and Model.objects.all().first() to retrieve first element in a queryset or using filters without a second thought. Then see some caveats below.
The important part to note here is that if you haven't included any ordering in your model the data can be in any order and you will have a random last or first element which was not expected.
Eg. Let's say you have a model named Model1 which has 2 columns id and item_count with 10 rows having id 1 to 10.[There's no ordering defined]
If you fetch Model.objects.all().last() like this, You can get any element from the list of 10 elements. Yes, It is random as there is no default ordering.
So what can be done?
You can define ordering based on any field or fields on your model. It has performance issues as well, Please check that also. Ref: Here
OR you can use order_by while fetching.
Like this: Model.objects.order_by('item_count').last()
If using django 1.6 and up, its much easier now as the new api been introduced -
Model.object.earliest()
It will give latest() with reverse direction.
p.s. - I know its old question, I posting as if going forward someone land on this question, they get to know this new feature and not end up using old method.
In a Django template I had to do something like this to get it to work with a reverse queryset:
thread.forumpost_set.all.last
Hope this helps someone looking around on this topic.
MyModel.objects.order_by('-id')[:1]
If you use ids with your models, this is the way to go to get the latest one from a qs.
obj = Foo.objects.latest('id')
You can try this:
MyModel.objects.order_by('-id')[:1]
The simplest way, without having to worry about the current ordering, is to convert the QuerySet to a list so that you can use Python's normal negative indexing. Like so:
list(User.objects.all())[-1]