How to get id of newly added child item in Python SQLAlchemy? - python

I have these code written in Python using SQLAlchemy.
dailyCashFlow = models.DailyCashFlow(day=day, cash_start_of_day = cash_start_of_day, cash_end_of_day = cash_end_of_day)
branch.dailyCashFlow.append(dailyCashFlow)
db.session.commit()
result['result'] = True
result['message'] = string.join(['Daily cashflow saved successfully with ID=#'], `dailyCashFlow.id`)
The relationship is roughly : company->branches->dailyCashflow.
I want to get the id of the newly inserted dailyCashFlow.id. I think I can easily refer back to dailyCashFlow object to get the id, but it's not. It use lazy='dynamic' set up in the model. Is that the reason? And, how can I easily get the id of the newly inserted data?

Do your mean is got id by inserted data?
result = tb_conn.insert().execute(data)
id = result.inserted_primary_key[0]

I pasted my revelation to this questio
"You're right zzzeeek! That is also my understanding, if you inspect closely this code, string.join(['Daily cashflow saved successfully with ID=#'], dailyCashFlow.id), you will see that the ] is introduce too early. It should be like this : string.join(['Daily cashflow saved successfully with ID=#', dailyCashFlow.id)]. Well, I guess now I get a good experience why unit test is a must.. :) - If you want moving your reply to question section, I would gladly accept it as the accepted answer. "
So visitor to this page will know what did I do wrong ;)

Related

Stripe API: filter for Payout ID when I have destination ID (bank ID)

I'm using python. I am trying to retrieve all payouts to a certain destination.
The code for retrieving everything is:
stripe.Payout.list(limit=3)
How do I add a parameter containing the destination ID? (Destination ID is in this form: ba_XXXXXXXXXXXXXXXXX)
I actually figured it out. This is not included in stripe API documentation. Just add a field like this:
stripe.Account.retrieve(destination = "ba_XXXXXXXXXXXXXXXX")
The only problem is this doesn't allow NOT filters. I can't do !=. It has to be = only. I haven't tried with > or <. Can anyone help me with this?

How to print particular id(i.e word ) from the result

Hi i have the following code:
Z = [ [<Entity:0*7fasdas55c:type1101(1101,NGRID)id:-2600>, <Entity:0*5fafaef45c:type1101(1101,NGRID)id:-3665>]
, [<Entity:0*7fasdas55c:type1101(1101,NGRID)id:-5600>, <Entity:0*5fafaef45c:type1101(1101,NGRID)id:-545465>] ]
edge1= ansa.basecollectentity(constant.nastran, Z[0],'NODE')
print(edge1)
and my result is
[<Entity:0*7fasdas55c:type1101(1101,NGRID)id:-2600>, <Entity:0*5fafaef45c:type1101(1101,NGRID)id:-3665>]
Enen though code is written in ansa python, my question is General
I would like to write a code such that it goes through the 'edge1' and prints the number after ids with two different names: like
Node1= 2600
Node2= 3665
Pls help me with writing the code, thanks in advance
Each class controls its own printable representation with the __repr__() special method.
The number you're looking at, id: could potentially be anywhere in the Entity, in any field, or somewhere in an internal datastructure, or nowhere and calculated at display time. It might easily be an id property as #PM2Ring's comment suggests - but it might not be.
So it's either a very specific question - you need to examine the Entity for an appropriate field or method to get the ID. And you haven't said what it is, so that could be anything.
Or it's a general question about processing the repr() value - which is probably not what you want to do ever, really.
But if you did want to, it would be:
for count, item in enumerate(edge1):
id = repr(item).split(':')[-1].rstrip('>')
print "Node" + str(count), id
in ansa say you have a entity eg:
nod=<Entity:0*7fasdas55c:type1101(1101,NGRID)id:-2600>
to print id you can use:
Print(nod._id)
result:
2600
you can also use ._type to get the type of entity you are dealing with
hope it helps

python database table linking

I'm new to Python and I'm trying to make a simple bulletin board system app using web2py. I am trying to add a post into a certain board and I linked the post and board by including the following field in my post table: Field('board_id', db.board). When I try to create a post inside a particular board it gives me an error: "OperationalError: no such column: board.id". My code for create_posts:
def add_post():
board = db.board(request.args(0))
form = SQLFORM(db.post)
db.pst.board_id.default = db.board.id
if form.process().accepted:
session.flash = T('The data was inserted')
redirect(URL('default', 'index'))
return dict(form=form, board=board)
When I try to do {{=board}} on the page that shows the posts in a certain board, I get Row {'name': 'hi', 'id': 1L, 'pst': Set (pst.board_id = 1), 'description': 'hi'} so I know it's there in the database. But when I do the same thing for the "add post" form page, it says "board: None". I'm extremely confused, please point me in the right direction!
There appear to be several problems with your function. First, you are assigning the default value of the board_id field to be a Field object (i.e., db.board.id) rather than an actual id value (e.g., board.id). Second, any default values should be assigned before creating the SQLFORM.
Finally, you pass db.post to SQLFORM, but in the next line, the post table appears to be called db.pst -- presumably these are not two separate tables and one is just a typo.
Regarding the issue of {{=board}} displaying None, that indicates that board = db.board(request.args(0)) is not retrieving a record, which would be due to request.args(0) itself being None or being a value that does not match any record id in db.board. You should check how you are generating the links that lead to add_post and confirm that there is a valid db.board id in the first URL arg. In any case, it might be a good idea to detect when there is no valid board record and either redirect or display an error message.
So, your function should look something like this:
def add_post():
board = db.board(request.args(0)) or redirect(URL('default', 'index'))
db.pst.board_id.default = board.id
form = SQLFORM(db.pst)
if form.process(next=URL('default', 'index'),
message_onsuccess=T('The data was inserted'))
return dict(form=form, board=board)
Note, if your are confident that links to add_post will include valid board IDs, then you can eliminate the first line altogether, as there is no reason to retrieve a record based on its ID if the only field you need from it is the ID (which you already have). Instead, the second line could be:
db.pst.board_id.default = request.args(0) or redirect(URL('default', 'index'))

How to add value to a column in a record which is already saved in django

I am trying to save a data in to a column but that record is already saved. I am working with django and sql
models.py
class P(models.Model):
t=models.ForeignKey(T)
q=models.TextField(max_length=500)
c_a=models.IntegerField(null=True)
I have other classes in the models.py
views.py
...
P_object=P(t_id=T_object.id, q=q)
P_object.save()
...
here i am saving only two columns and i want the third column to be saved separately later when i get an id from a other record
A_object=A(q_id = q_object.id, a=a)
A_object.save()
P_object.c_a = A_object.id
But this code does not seem to work. Am i doing it wrong?
"doesn't seem to work" is about as useless a problem's description can be. You've got the first two points ("here's what I do", "here's what I expect") right but you're missing the third one : "here's what I get". But anyway...
A_object=A(q_id = q_object.id, a=a)
A_object.save()
P_object.c_a = A_object.id
Model instances are not automagically saved when modified, you have to save them by yourself. Just add
P_object.save()
and you should be fine. Else please post the whole traceback.
As a side note, any reason you don't use amodels.ForeignKey field instead ?
try:
class P(models.Model):
t=models.ForeignKey(T)
q=models.TextField(max_length=500,blank=True)
c_a=models.IntegerField(max_length=30,blank=True,null=True)
if it doesn't solved the problem, then may be the P_object not defined(scope expired)
find the P_object using objects.get and save it again.
A_object=A(q_id = q_object.id, a=a)
A_object.save()
P_object=P.objects.get(t_id=T_object.id)
P_object.c_a = A_object.id
P_object.save()

figuring out the possible attributes of an object

regarding this code from python-blogger
def listposts(service, blogid):
feed = service.Get('/feeds/' + blogid + '/posts/default')
for post in feed.entry:
print post.GetEditLink().href.split('/')[-1], post.title.text, "[DRAFT]" if is_draft(post) else ""
I want to know what fields exist in feed.entry but I'm not sure where to look in these docs to find out.
So I dont just want an answer. I want to know how I should've navigated the docs to find out for myself.
Try dir(field.entry)
It may be useful for your case.
It's a case of working through it, step by step.
The first thing I did was click on service on the link you sent... based on service = feed.Get(...)
Which leads here: http://gdata-python-client.googlecode.com/hg/pydocs/gdata.service.html
Then looking at .Get() it states
Returns:
If there is no ResultsTransformer specified in the call, a GDataFeed
or GDataEntry depending on which is sent from the server. If the
response is niether a feed or entry and there is no ResultsTransformer,
return a string. If there is a ResultsTransformer, the returned value
will be that of the ResultsTransformer function.
So guessing you've got a GDataFeed - as you're iterating over it:, and a quick google for "google GDataFeed" leads to: https://developers.google.com/gdata/jsdoc/1.10/google/gdata/Feed

Categories

Resources