How to extract FreeText answer from an assignment using boto - python

I'm trying to extract free-text answer submitted by workers of Amazon Mechanical Turk using the boto library.
assignments = conn.get_assignments(hit_id)
for assignment in assignments:
worker = assignment.WorkerId
answer = assignment.Answer
Here I expect answer to be a free-text string (the only thing that the HIT asks workers to submit) submitted by a worker, however, the code above doesn't give me that. What am I missing here?

In boto in order to get the FreeText information you are looking for, you'll need to iterate over the assignment property answers. Unless you have submitted multiple forms, your form should be the first index.
This list is of type QuestionFormAnswer
Here is boto documentation on QuestionFormAnswer
http://sourcecodebrowser.com/python-boto/2.3.0/classboto_1_1mturk_1_1connection_1_1_question_form_answer.html
You can see that the properties you actually want are qid and fields
Here is some updated code that should make better sense.
assignments = conn.get_assignments(hit_id)
for assignment in assignments:
worker_id = assignment.WorkerId
# Iterate through question forms answers which are our fields
for question_form_answer in assignment.answers[0]:
field_id = question_form_answer.qid
field_value = question_form_answer.fields

I think the assignment object in the above example will have an attribute called answers which is a list of QuestionFormAnswer objects. Each of these objects should have an attribute called FreeText.

Related

How to get Document Name from DocumentReference in Firestore Python

I have a document reference that I am retreiving from a query on my Firestore database. I want to use the DocumentReference as a query parameter for another query. However, when I do that, it says
TypeError: sequence item 1: expected str instance, DocumentReference found
This makes sense, because I am trying to pass a DocumentReference in my update statement:
db.collection("Teams").document(team).update("Dictionary here") # team is a DocumentReference
Is there a way to get the document name from a DocumentReference? Now before you mark this as duplicate: I tried looking at the docs here, and the question here, although the docs were so confusing and the question had no answer.
Any help is appreciated, Thank You in advance!
Yes,split the .refPath. The document "name" is always the last element after the split; something like lodash _.last() can work, or any other technique that identifies the last element in the array.
Note, btw, the refPath is the full path to the document. This is extremely useful (as in: I use it a lot) when you find documents via collectionGroup() - it allows you to parse to find parent document(s)/collection(s) a particular document came from.
Also note: there is a pseudo-field __name__ available. (really an alias of documentID()). In spite of it's name(s), it returns the FULL PATH (i.e. refPath) to the document NOT the documentID by itself.
I think I figured out - by doing team.path.split("/")[1] I could get the document name. Although this might not work for all firestore databases (like subcollections) so if anyone has a better solution, please go ahead. Thanks!

Pass many-to-many object to variable

I have 2 classes, with many-to-many relationship, my goal is to fill an 'item' list with data from that 2 models, here are my models:
class Bakery(models.Model):
title = models.CharField('restaurant_name', max_length=100)
class DeliveryService(models.Model):
title = models.CharField('deliveryservice_name', max_length=100)
bakery = models.ManyToManyField(Bakery)
Here is the logic on my 'views' file:
item = []
bakerys = Bakery.objects.all()
for i in bakerys:
item.append(i.title)
item.append(i.deliveryservice.title)
I hope you got what exactly I want to accomplish. My current 'views' file logic is wrong and I know it, I just does not know what can I do to solver this problem. Thank you for your time.
The following seems to do what you're asking for. But it seems odd that you want to create a list with all the titles for different objects all mixed together and likely have duplicates (if a delivery service is linked to more than one bakery it'll be added twice).
item = []
bakerys = Bakery.objects.all()
for i in bakerys:
item.append(i.title)
for j in i.deliveryservice_set.all():
item.append(j.title)
You should really read up on the many-to-many functionality of the ORM. The documentation is pretty clear on how to do these things.
Sayse had a good answer too if you really just want all the titles. Their answer also groups everything in tuples and accomplishes it with more efficiency by using fewer db queries. Their answer was: Bakery.objects.values('title', 'deliveryservice__title')

Getting the upvotes of an answer using Py-Stackexchange

I'm using Py_Stackexchange to pull data from Stackoverflow for some statistical analysis, and stumbled upon a problem.
I need to retrieve the upvotes and downvotes on an answer. I have the stackexchange.Answer object, and it has a field called 'transfers' which is a tuple of strings like:
'is_accepted', 'locked_date', 'question_id', 'up_vote_count', 'down_vote_count',
'view_count', 'score', 'community_owned', 'title', 'body'
How do I get the actual numerical values corresponding to these fields?
I utilized the question demo, provided by Py-Stackexchange for this answer.
The biggest thing you need to do is ensure that your filter includes the up_vote_count and down_vote_count attributes.
Once you have this filter, you can access the value by question.up_vote_count (or answer.up_vote_count if you are checking an answer).
As an example, I modified line 22 in the demo, to include these two attributes in the filter:
question = site.question(id, filter="!b0OfMwwD.s*79x")
Filters can be created here.
Then I added this line at the very end of the script:
print('%d Upvotes.' % question.up_vote_count)
When I run it against this question, I get this output:
Please enter an API key if you have one (Return for none):
Enter a question ID: 26143702
--- Getting the upvotes of an answer using Py-Stackexchange ---
<p>I'm using <code>Py_Stackexchange</code> to pull data from <code>Stackoverflow</code> for some statistical analysis, and stumbled upon a problem.</p>
<p>I need to retrieve the upvotes and downvotes on an answer. I have the <code>stackexchange.Answer</code> object, and it has a field called 'transfers' which is a tuple of strings like:</p>
<pre><code>'is_accepted', 'locked_date', 'question_id', 'up_vote_count', 'down_vote_count',
'view_count', 'score', 'community_owned', 'title', 'body'
</code></pre>
<p>How do I get the actual numerical values corresponding to these fields?</p>
0 answers.
1 Upvotes.

filter() method in python django

out_links = Link.objects.filter(iweb=iweb_id).order_by('-pub_date')
for link in out_links:
comments = LinkComment.objects.filter(link=link.id)
Filter method creates the list of object, so out_links is a list, right ?
Next, after for loop, I filtering again to find objects in LinkComments class by link id.
The question arises though, shoud I refer to link as it would be the object or rather a list?
I'm not shure about it as long it is django views? link.id or link['id']? My python says [ ], but django does not work.
The out_links is a queryset and in the for loop you can reach all LinkComments by:
for link in out_links:
comments = link.linkcomment_set.all()
Filter creates a QuerySet, as explained in the documentation: https://docs.djangoproject.com/en/dev/ref/models/querysets/#methods-that-return-new-querysets
If you subscript a QuerySet, like comments[n], you get the nth member (just as you would with a list). Where you have an order_by, that is in the order specified by that clause. You cannot query by id using the subscript notation.
When you iterate over the QuerySet, you get the members of the queryset, which are python model objects, and you may treat them just as you do anywhere else in your code.
Filter method creates the list of object, so out_links is a list,
right ?
Wrong. It creates QuerySet object, which also happens to be an iterable.

Python - reading checkboxes

I have a few checkboxes with common name and individual variables (ID).
How can I in python read them as list?
Now I'm using
checkbox= request.POST["common_name"]
It isn't work properly, checkbox variable store only the last checked box instead of any list or something.
If you were using WebOB, request.POST.getall('common_name') would give you a list of all the POST variables with the name 'common_name'. See the WebOB docs for more.
But you aren't - you're using Django. See the QueryDict docs for several ways to do this - request.POST.getlist('common_name') is one way to do it.
checkbox = request.POST.getlist("common_name")
And if you want to select objects (say Contact objects) based upon the getlist list, you can do this:
selected_ids = request.POST.getlist('_selected_for_action')
object_list = Contact.objects.filter(pk__in=selected_ids)

Categories

Resources