How to search via production_id? - python

I am attempting to get a field from a manufacturing order to a related work order.
I have tried:
for record in records:
if record.production_id:
so = env['mrp.production'].search([('name', '=', record.production_id)])
if so:
record.write({"x_customer": so.x_customer_nick_name})
This however does not work, but if I do a search of the actual production ID name for manufacturing name it works as intended:
for record in records:
if record.production_id:
so = env['mrp.production'].search([('name', '=', record.'Boost/BoMO/73222')])
if so:
record.write({"x_customer": so.x_customer_nick_name})
I believe this is due to production_id, from the raw data I can see it is [11212,'Boost/BoMO/73222'].
So I only need the first element, however:
so = env['mrp.production'].search([('name', '=', record.production_id[1])])
does not return the string name of the production_id. How should I go about getting this data?
Error Code
pobjs = [adapt(o) for o in self._seq]\npsycopg2.ProgrammingError: can\'t adapt type \'dict\'\n'>

Please try this if production_id is of mrp.production relation:
if record.production_id:
so = record.production_id
If so:
record.write({"x_customer":so.x_customer_nick_name})
production_id is a Many2One field to mrp.production, so you can use it to access any field in mrp.production, and in your case you'd like to get the name of the manufacturing order so it should be something like the following:
so = self.env['mrp.production'].search([('name', '=', record.production_id.name)])

Wasn't able to find a solution here or on the odoo forums. For anyone else looking for a solution, I ended up using the web API. I scraped the work orders and the production ID manufacture orders. Built a tuple wrote to WO with a loop.
models.execute_kw(db, uid, password, 'mrp.workorder', 'write', [workorders_id, {
'x_for_customer': x_customer_nick_name}
}])

Related

Update custom_fields with Python in asana API

I've been trying update custom_fields per the latest version of Asana's API, very similarly to this post but with a later version of the API (e.g. I need to use update_task method). I can update fields at the top level of a task, but the custom_fields object is proving much more challenging to update. For example, I have many custom fields, and am trying to update a test field called "Update" and just set the text_value to "Hello"...
import asana
asanaPAT = 'myToken'
client = asana.Client.access_token(asanaPAT)
result = client.tasks.get_tasks({'project': 'myProjectID'}, opt_pretty=True)#, iterator_type=None)
for index, result in enumerate(result):
complete_task = client.tasks.find_by_id(result["gid"])
task_name = complete_task['name']
task_id = complete_task['gid']
custom_fields = complete_task['custom_fields']
#I can easily update top-level fields like 'name' and 'completed'...
#result = client.tasks.update_task(task_id, {'name': task_name + '(new)'}, opt_pretty=True)
#result = client.tasks.update_task(task_id, {'completed': False}, opt_pretty=True)
for custom_fieldsRow in custom_fields:
if custom_fieldsRow['name'] == "Updated":
#custom_fieldsRow['text_value'] = 'Hello'
#finished loop through individual custom fields, so update on the level of the task...
#client.tasks.update_task(task_id, {custom_fields}, opt_pretty=True)
manualCustomField = {'data': { 'custom_fields': {'gid': 'theGIDOfCustomField', 'text_value': 'Hello'} }}
resultFromUpdate = client.tasks.update_task(task_id, manualCustomField, opt_pretty=True)
As you can see above, I started off trying to loop through the custom_fields and make changes to the specific field before updating later. But now I'm even trying to manually set the custom_field data (last line of my code), but it does nothing (no error, but doesn't change my task). I'm completely out of ideas to troubleshoot this so appreciate any feedback on where I'm going wrong.
Apologies, I figured out my mistake, I just needed my penultimate line to read...
manualCustomField = { 'custom_fields': {'theGIDOfCustomField':'Hello'} }
Kinda a strange way to do that in the API (not specifically stating which field you'll update or which id you're using) if you ask me, but now it finally works.

How do I retrieve a path's data from firebase database using python?

I have this firebase database structure
I want to print out the inventory list(Inventory) for each ID under Businesses.
So I tried this code
db = firebase.database()
all_users = db.child("Businesses").get()
for user in all_users.each():
userid = user.key()
inventorydb = db.child("Businesses").child(userid).child("Inventory")
print(inventorydb)
but all I got is this
<pyrebase.pyrebase.Database object at 0x1091eada0>
what am I doing wrong and how can I loop through each Business ID and print out their inventory?
First, you're printing a Database object. You need to get the data still.
You seem to already know how to get that as well as the children. Or you only copied the examples without understanding it...
Either way, you can try this
db = firebase.database()
businesses = db.child("Businesses")
for userid in businesses.shallow().get().each():
inventory = businesses.child(userid).child("Inventory").get()
print( inventory.val() )
On a side note, National_Stock_Numbers looks like it should be a value of the name, not a key for a child

Python, CouchDb: how to Update already existing document by ID

I am trying to update an already existing document by ID. My intention is to find the doc by its id, then change its "firstName" with new value coming in "json", then update it into the CouchDB database.
Here is my code:
def updateDoc(self, id, json):
doc = self.db.get(id)
doc["firstName"] = json["firstName"]
doc_id, doc_rev = self.db.save(doc)
print doc_id, doc_rev
print "Saved"
//"json" is retrieved from PUT request (request.json)
at self.db.save(doc) I'm getting exception as "too many values to unpack".
I am using Bottle framework, Python 2.7 and Couch Query.
How do I update the document by id? what is the right way to do it?
In couchdb-python the db.save(doc) method returns tuple of _id and _rev. You're using couch-query - a bit different project that also has a db.save(doc) method, but it returns a different result. So your code should look like this:
def updateDoc(self, id, json):
doc = self.db.get(id)
doc["firstName"] = json["firstName"]
doc = self.db.save(doc)
print doc['_id'], doc['_rev']
print "Saved"

Updating DataStore JSON values using endpoints (Python)

I am trying to use endpoints to update some JSON values in my datastore. I have the following Datastore in GAE...
class UsersList(ndb.Model):
UserID = ndb.StringProperty(required=True)
ArticlesRead = ndb.JsonProperty()
ArticlesPush = ndb.JsonProperty()
In general what I am trying to do with the API is have the method take in a UserID and a list of articles read (with an article being represented by a dictionary holding an ID and a boolean field saying whether or not the user liked the article). My messages (centered on this logic) are the following...
class UserID(messages.Message):
id = messages.StringField(1, required=True)
class Articles(messages.Message):
id = messages.StringField(1, required=True)
userLiked = messages.BooleanField(2, required=True)
class UserIDAndArticles(messages.Message):
id = messages.StringField(1, required=True)
items = messages.MessageField(Articles, 2, repeated=True)
class ArticleList(messages.Message):
items = messages.MessageField(Articles, 1, repeated=True)
And my API/Endpoint method that is trying to do this update is the following...
#endpoints.method(UserIDAndArticles, ArticleList,
name='user.update',
path='update',
http_method='GET')
def get_update(self, request):
userID = request.id
articleList = request.items
queryResult = UsersList.query(UsersList.UserID == userID)
currentList = []
#This query always returns only one result back, and this for loop is the only way
# I could figure out how to access the query results.
for thing in queryResult:
currentList = json.loads(thing.ArticlesRead)
for item in articleList:
currentList.append(item)
for blah in queryResult:
blah.ArticlesRead = json.dumps(currentList)
blah.put()
for thisThing in queryResult:
pushList = json.loads(thisThing.ArticlesPush)
return ArticleList(items = pushList)
I am having two problems with this code. The first is that I can't seem to figure out (using the localhost Google APIs Explorer) how to send a list of articles to the endpoints method using my UserIDAndArticles class. Is it possible to have a messages.MessageField() as an input to an endpoint method?
The other problem is that I am getting an error on the 'blah.ArticlesRead = json.dumps(currentList)' line. When I try to run this method with some random inputs, I get the following error...
TypeError: <Articles
id: u'hi'
userLiked: False> is not JSON serializable
I know that I have to make my own JSON encoder to get around this, but I'm not sure what the format of the incoming request.items is like and how I should encode it.
I am new to GAE and endpoints (as well as this kind of server side programming in general), so please bear with me. And thanks so much in advance for the help.
A couple things:
http_method should definitely be POST, or better yet PATCH because you're not overwriting all existing values but only modifying a list, i.e. patching.
you don't need json.loads and json.dumps, NDB does it automatically for you.
you're mixing Endpoints messages and NDB model properties.
Here's the method body I came up with:
# get UsersList entity and raise an exception if none found.
uid = request.id
userlist = UsersList.query(UsersList.UserID == uid).get()
if userlist is None:
raise endpoints.NotFoundException('List for user ID %s not found' % uid)
# update user's read articles list, which is actually a dict.
for item in request.items:
userslist.ArticlesRead[item.id] = item.userLiked
userslist.put()
# assuming userlist.ArticlesPush is actually a list of article IDs.
pushItems = [Article(id=id) for id in userlist.ArticlesPush]
return ArticleList(items=pushItems)
Also, you should probably wrap this method in a transaction.

Unable to view item in browser based on its key in Python GAE

I'm using python GAE with webapp.
I have a form for a user to create a object in the database, something like:
class SpamRecord(db.Model):
author = db.ReferenceProperty(Author, required=True)
text = db.StringProperty()
After it's created, the user is redirected to a page whose URL contains that object's key... using code such as:
spam = SpamRecord(author=author, text=text)
spam.put()
new_spam_key = spam.key()
self.redirect("/view_spam/%s" % new_spam_key)
And this mostly works, with me being able to view items at:
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQYy8oJDA
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY_boJDA
However, there's an occasional key that won't work. Here are 2 recent examples of pages that won't load and return HTTP 404 not found errors:
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-5MJDA
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-boJDA
My html-mappings.py contains the following mapping:
(r"/view_spam/(\w+)", ViewSpamPage)
And the ViewSpamPage looks something like:
class ViewSpamPage(webapp.RequestHandler):
def get(self, spam_id):
self.response.out.write("Got here")
Can anyone offer any insight as to why this is occurring and how it may be prevented?
Thanks very much!
In regular expressions, \w doesn't match hyphens. (It will match underscores.) For that second pair of keys, this'll result in only passing part of the key to your handler.
In your URL pattern, try r"/view_spam/(.*)" instead.

Categories