[Grok-dev] Re: Referencing objects by id
Philipp von Weitershausen
philipp at weitershausen.de
Sun Aug 3 06:35:15 EDT 2008
Gerard Petersen wrote:
> Hi All,
>
> 1st, forgive my n00bishness. I'm on Grok for a net time of only a couple
> of days now. Anyway ..
>
> Im trying to get my head around storing objects (Customers that is)
> based on customer id's. An url should look like this:
>
> http://localhost:8080/gpadmin/1
>
> It was previously (working and) based on company name and used to look
> like this:
>
> http://localhost:8080/gpadmin/Customer
>
> I use zope's interface and schema to work with the model and suppress
> the id field in forms with:
>
> "form_fields = grok.AutoFields(Customer).omit('id')"
>
> Because of this I have to calculate a new id before storing a new
> customer object. From a MVC perspective I think the 'get new id' code
> belongs in the model class but that's a different story.
Sure, you can do that. However, you probably want these IDs to be unique
throughout a particular range, so the model would have to know about
existing IDs somehow. That typically means it needs to know at creation
time which container it's being added to.
> The error I get wanting to set the value for id is this:
>
> TypeError: 'Customer' object does not support item assignment
>
> The snippet I use it in is this:
>
> def handle_voeg_toe(self, **data):
> customer = Customer()
>
> values = list(self.context.values())
> new_id = str(len(values) + 1)
>
> # It breaks here!!!!
> customer['id'] = new_id
You're doing item assignment here but that's typically only supported by
dict-like objects (e.g. containers). Hence the error message that it
doesn't support item assignment.
You want to assign a simple attribute:
customer.id = new_id
> self.context['id'] = customer
> self.applyData(customer, **data)
> self.redirect(self.url('index'))
>
>
> Changing/replacing the line in the snippet after the break point with this:
>
> self.context[new_id] = customer
>
> Seemingly works because I can use this:
>
> http://localhost:8080/gpadmin/1
>
> But then the actual 'id' attribute is not filled.
>
> If more code or information is needed to clearify I'll gladly post it,
> but I consider this email long already ... :-)
More information about the Grok-dev
mailing list