peewee get_or_create and then save: error binding - peewee

Is there an easy way to update a field on a get of a get_or_create?
I have a class ItemCategory and I want to either create a new entry or get the already created entry and update a field (update_date).
What I do is:
item,created= ItemCategory.get_or_create(cat=cat_id,item=item_id)
if created == True:
print "created"
else:
item.update_date = datetime.now
item.somethingelse = 'aaa'
item.save()
This works for a while in my loop. But after 50-100 get/create it crashes:
peewee.InterfaceError: Error binding parameter 4 - probably unsupported type.
Maybe I should use upsert(), I tried but wasn't able to get anything working. Also it's not probably the best solution, since it makes a replace of the whole row instead of just a field.
I like peewee, it's very easy and fast to use, but I can't find many full examples and that's a pity

Newbie mistake
item.update_date = datetime.now()
I am not 100% sure this is the only answer though. I modified my code so many times that it might be also something else.
Regarding my question about create_or_update , I've done this:
try:
Item.create(...)
except IntegrityError:
Item.update(...)
peewee is really great, I wonder why no one ever asked for a create_or_update.

Related

Best, Better, or Simpler Way to Get the Label for a Content-Type's Field

I thought I was doing something easy, but it got so complicated that I feel like I am missing something. We have a Content-Type (CT) that moves through a workflow. In each phase of the workflow, the output changes which fields are visible.
We want to easily access both the record's Value and Label. In other words, lets say we have a CT named EventInstance and one of fields is Url. So in code we normally just do #Content.Url. However, for table headings (and in other output) we want to display "Website Link (Url)" instead of "Url". So in the CT we simply changed the Name* (Label):
So then I went looking for how to get that "Label" field (2) instead of the Name (1). What I came up with was this. But it seems crazy complicated...
public string GetLabelForField(dynamic de, string fieldName)
{
var attributes = AsEntity(de).Type.Attributes as IEnumerable<IContentTypeAttribute>;
return attributes.First(t => t.Name == fieldName).Metadata.GetBestValue<string>("Name", "#All");
}
And I call it like this
var ev = listEvent.First();
<pre>
help.GetLabelForField(ev): #help.GetLabelForField(ev, "Url")
</pre>
And that outputs what I want:
help.GetLabelForField: Website Link (Url)
I realize I should be satisfied because it works, but it seems like a lot of work and a steep learning curve. Is there a better way to get access to this (seemingly common) property?
These APIs are not documented much, because accessing input-field configuration used in the Edit-UI isn't that common.
But: I believe you could also do this (shorter, but probably not perfect):
var attribute = AsEntity(de).Type[fieldName];
var name = attribute.Metadata.GetBestValue<string>("Name");

Identify one particular field with RegEx

Apologies for the basic question but I'm new to regular expressions and am really struggling to find a solution to the problem I am facing.
I am trying to pull out a particular field from a json response dynamically, which can change each time I call it.
The response is:
[{"colorPartNumber":"10045112022164298","skuPartNumber":"0400218072057","productColor":{"identifier":"Dark blue","label":"Dark blue","hex":"#0000A0"},"productSize":{"identifier":"0","label":"0","name":"Designer","scaleLabel":"apparel-wmn","schema":{"name":"UK","labels":["8"]}},"soldOut":true,"onlyOneLeft":false,"limitedAvailability":false,"preorder":false,"comingSoon":false,"visible":true,"displayable":true,"buyable":false,"availableInPhysicalStore":false,"expectedShippingDate":null},{"colorPartNumber":"10045112022164298","skuPartNumber":"0400094632819","productColor":{"identifier":"Dark blue","label":"Dark blue","hex":"#0000A0"},"productSize":{"identifier":"1","label":"1","name":"Designer","scaleLabel":"apparel-wmn","schema":{"name":"UK","labels":["10"]}},"soldOut":true,"onlyOneLeft":false,"limitedAvailability":false,"preorder":false,"comingSoon":false,"visible":true,"displayable":true,"buyable":false,"availableInPhysicalStore":false,"expectedShippingDate":null},{"colorPartNumber":"10045112022164298","skuPartNumber":"0400218072040","productColor":{"identifier":"Dark blue","label":"Dark blue","hex":"#0000A0"},"productSize":{"identifier":"2","label":"2","name":"Designer","scaleLabel":"apparel-wmn","schema":{"name":"UK","labels":["12"]}},"soldOut":true,"onlyOneLeft":false,"limitedAvailability":false,"preorder":false,"comingSoon":false,"visible":true,"displayable":true,"buyable":false,"availableInPhysicalStore":false,"expectedShippingDate":null},{"colorPartNumber":"10045112022164298","skuPartNumber":"0400468014814","productColor":{"identifier":"Dark blue","label":"Dark blue","hex":"#0000A0"},"productSize":{"identifier":"3","label":"3","name":"Designer","scaleLabel":"apparel-wmn","schema":{"name":"UK","labels":["14"]}},"soldOut":false,"onlyOneLeft":true,"limitedAvailability":false,"preorder":false,"comingSoon":false,"visible":true,"displayable":true,"buyable":true,"availableInPhysicalStore":false,"expectedShippingDate":null}]
I am trying to pull out the skuPartNumber, but only when the "buyable" value is set to true.
Every thing I try I cannot seem to get just this one value :(
So in the example above the only value I want to pull out is 0400468014814.
This json is dynamic so there could be 100 values coming back, but the principle is the same.
One example of a failed attempt is skuPartNumber(.*?)"buyable":true, which only gives me the very first value (0400218072057), which is wrong.
Once again sorry for the basic question.
Try the following regular expression:
\"skuPartNumber\":\"(\d+)\"(?:[^}]*?\}){3}[^}]*?\"buyable\":true
Your answer is in the first match group.

BadValueError: Expected GeoPt

I am trying to pass values from a html form into the gae datastore and receive the following error:
"BadValueError: Expected GeoPt, got (51.123, -0.123)"
Apologies up front, but I'm new to this so may be going about it all wrong but would really appreciate some advice on the best way of doing this.
Thanks in advance.
Looks like you're trying to assign a tuple to the property instead of a geopt.
Your code does this:
entity.some_geo_property = (51.123, -0.123)
Where it needs to do this:
from google.appengine.ext import ndb
entity.some_geo_property = ndb.GeoPt(51.123, -0.123)
alternatively using the tuple:
entity.some_geo_property = ndb.GeoPt(*value)
Without seeing your exact code it's hard to offer a complete solution. If you provide code I'll try to update my answer.
I have never worked with GeoPt properties, but I would think that you passed a tuple of two floats.
Pass the value to ndb.GeoPt() first and store the return value in NDB. Example:
location = ndb.GeoPt(51.123, -0.123)
If you use the DB API of HRD rathern than the NDB API, use db.GeoPt() which is basically the same.

Accessing variable from other class returns null

I did a separate levelData class to be able to flexibly add levels. I was happy with it until my supervisor ordered me to convert my levelData into XML. I did an XML version of the levelData's data (question, answers, correct answer...). I used the old class and converted it so that it fetches the XML.
All seems well, I did traces of my answers array and it printed nicely...
But the headache started when I tried this.
// This code appears in a different class with
// currentLvl:LevelData initialized in the constructor.
quizHolder.ansA.ansHud.text = currentLvl.choices[1];
quizHolder.ansB.ansHud.text = currentLvl.choices[2];
quizHolder.ansC.ansHud.text = currentLvl.choices[3];
quizHolder.ansD.ansHud.text = currentLvl.choices[4];
// BTW, I can't make a for loop to do the same function as above. So wierd.
I tried to run it. it returned:
TypeError: Error #2007: Parameter text must be non-null.
at flash.text::TextField/set text()
at QuestionPane/setQuiz()
at QuestionPane/setQuestion()
at QuestionPane()
at LearningModule()
Where did I go wrong? I tried making a custom get function for it, only to get the same error. Thanks in advance. If I need to post more of the code, I will gladly do so =)
LevelData Class in PasteBin: http://pastebin.com/aTKC1sBC
Without seeing more of the code it's hard to diagnose, but did you correctly initialize the choices Array before using it? Failing that I think you'll need to post more code.
Another possible issue is the delay in loading the XML data. Make sure your data is set before QuestionPane tries to access it.
When did you call
quizHolder.ansA.ansHud.text = currentLvl.choices[1];
quizHolder.ansB.ansHud.text = currentLvl.choices[2];
quizHolder.ansC.ansHud.text = currentLvl.choices[3];
quizHolder.ansD.ansHud.text = currentLvl.choices[4];
these? You load the XML and on complete you fill the array, what is correct. but is the XML loaded and parsed to the time when you access (fill the TextFields) the choices array already?

C#, Linq data from EF troubles

I don't have much experience with programming. I am working (to learn) on a project. I am using C# 4.0 and WPF 4 with EF (SQLite). I am having problemw with LINQ.
Here is the code in question (I hope this is enough, let me know if more is needed)
private void cboSelectCompany_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
using (ShippingEntities context = new ShippingEntities())
{
var companies = from company in context.Deliveries
where company.State == cboSelectCompany.SelectedItem.ToString()
select company;
txtDeliveryName.Text = companies.Name;
txtDeliveryState.Text = companies.State;
}
The last two lines don't work. Am I misunderstanding what LINQ is returning? I just get this error
Error 5 'System.Linq.IQueryable<SqliteDemo.Delivery>' does not contain a definition for 'State' and no extension method 'State' accepting a first argument of type 'System.Linq.IQueryable<SqliteDemo.Delivery>' could be found (are you missing a using directive or an assembly reference?) c:\users\dan\documents\visual studio 2010\Projects\SqliteDemo\SqliteDemo\DeliveryCompanies.xaml.cs 49 51 SqliteDemo
If anyone could give me some pointers or to a good reference I would appreciate it
You're close!
Linq is returning a Queryable set of Deliveries, which hasn't executed yet. My guess based on reading your code is that you're expecting at most one result, and then you want to put those values into a UI of some sort. In that case what you'll want to do is:
Take your IQueryable and execute it
Make sure you grab the first (or, alternatively enforce that there is only one) row
Set the appropriate values in the UI.
So, leave the line with the query there, and then change the rest to something like this:
var company = companies.FirstOrDefault();
txtDeliveryName.Text = company.Name;
txtDeliveryState.Text = company.State;
Insert null-checking as appropriate, and go check out the differences between First, FirstOrDefault, Single, and SingleOrDefault to see which one seems most correct for your particular situation.
Well, looks like companies.State doesn't compile, because companies is a list of SqliteDemo.Delivery (and not just a SqliteDemo.Delivery).
What do you want to achieve? Imagine that your LINQ query returns several results, is it possible?
Just use companies.FirstOrDefault() or companies.Single() to access first item becouse by default LINQ returns collection of items not just single item.

Resources