How to get the last changed object in django-simple-history? - django-simple-history

Using django-simple-history, how can I get the last changed object from my model?
I tried MyModel.history.most_recent(), which needs a model instance, so that returns probably the most recent version of a selected instance.
I can query Abonnent.history.all(), which obviously returns a list of all versions of all model objects. This looks good, but how can I filter out the most recent and get the date of the last change?

If MyModel.history is a HistoricalRecords objects you access like:
MyModel.history.last()

What about:
from datetime import datetime
poll.history.as_of(datetime(2010, 10, 25, 18, 4, 0))
<Poll: Poll object as of 2010-10-25 18:03:29.855689>
poll.history.as_of(datetime(2010, 10, 25, 18, 5, 0))
<Poll: Poll object as of 2010-10-25 18:04:13.814128>

Related

How to set a default value to server generated time?

Is is possible to have a datetime field which has as a default server generated time during save?
class ADoc(Document):
...
created_at = me.DateTimeField(default=datetime.datetime.utcnow)
This model has two issues:
created_at will get a value during model instance creation, not the time when the document is saved into the database.
Client time is used, which might differ from the server time -- I'd like to always use server time as the time source.
Maybe you can use the operator $currentDate ?
UPD:
I like pymongo, but I think that can be for MongoEngine, you can try:
collection = Animal._get_collection()
collection.update({}, {"$currentDate": {"date": 1}}, upsert=true)
example here
By default the _id field contains the timestamp on creation.
You can access it like this ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp().
There's also $currentDate and new Date.
I would use defined by me insert method in my ADoc class:
from datetime import datetime
class ADoc:
def __init__(self, db, config):
self.docs= db['docs']
self.config = config
def insert(self, document):
item = {
'name': document['name'],
'created': datetime.utcnow()
}
self.docs.insert_one(item)
then simply execute the method when needed
client = MongoClient(DB_URL)
db = client['yourDb']
doc = "your new doc"
adoc = ADoc(db, app.config)
adoc.insert(doc)

I would like to store the values in array list after iterating the select options , is it possible in Watir

I am trying to store the values of select list in an array variable
a = b.options.each {|option| puts option.attribute_value "value" }
Output :
IN PROGRESS
UPCOMING
FINAL
POSTPONED
CANCELLED
a.to_i
Is it possible to store all values which getting from attribute and store in An array
The element collections in Watir include the Enumerable module, which gives a lot of useful methods for iterating. In particular, it includes a map method that will perform a block on each element and collect the result in an array.
To store the value of all options, you can simply do:
total_list_values = #browser.options.map(&:value)
#=> ["IN PROGRESS", "UPCOMING", "FINAL", "POSTPONED", "CANCELLED"]
I coded it like this and its worked, posted if anyone wanted this
total_list_values = Array.new
body = #browser.options
body.options.each do |option|
total_list_values << option.value
end

How to get Order Time in Magento?

I am trying to rewrite my PDF invoices in Magento. How can i display the created time without the date of a Order?
I am preparing the class insertOrder() in /app/code/local/Mage/Sales/Model/Order/Pdf/Abstract.php.
$page->drawText(Mage::helper('core')->formatDate($order->getCreatedAtStoreDate(), 'short', false), 100, 100, 'UTF-8');
shows only the time in combination with date.
One way to display the time part only would be this:
$sTime = Mage::app()
->getLocale()
->date(strtotime($order->getCreatedAtStoreDate()), null, null, false)
->toString('H:m:s');
$page->drawText($sTime, 100, 100, 'UTF-8');
Magento's locale uses a modified Zend_Date class for date/time operations.
See the toString() method of app/code/core/Zend/Date.php for parameter infos.

How to get the object id in PyMongo after an insert?

I'm doing a simple insert into Mongo...
db.notes.insert({ title: "title", details: "note details"})
After the note document is inserted, I need to get the object id immediately. The result that comes back from the insert has some basic info regarding connection and errors, but no document and field info.
I found some info about using the update() function with upsert=true, I'm just not sure if that's the right way to go, I have not yet tried it.
One of the cool things about MongoDB is that the ids are generated client side.
This means you don't even have to ask the server what the id was, because you told it what to save in the first place. Using pymongo the return value of an insert will be the object id. Check it out:
>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> _id = collection.insert({"name": "tyler"})
>>> print _id.inserted_id
4f0b2f55096f7622f6000000
The answer from Tyler does not work for me.
Using _id.inserted_id works
>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> _id = collection.insert({"name": "tyler"})
>>> print(_id)
<pymongo.results.InsertOneResult object at 0x0A7EABCD>
>>> print(_id.inserted_id)
5acf02400000000968ba447f
It's better to use insert_one() or insert_many() instead of insert(). Those two are for the newer version. You can use inserted_id to get the id.
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
myDB = myclient["myDB"]
userTable = myDB["Users"]
userDict={"name": "tyler"}
_id = userTable.insert_one(userDict).inserted_id
print(_id)
Or
result = userTable.insert_one(userDict)
print(result.inserted_id)
print(result.acknowledged)
If you need to use insert(), you should write like the lines below
_id = userTable.insert(userDict)
print(_id)
Newer PyMongo versions depreciate insert, and instead insert_one or insert_many should be used. These functions return a pymongo.results.InsertOneResult or pymongo.results.InsertManyResult object.
With these objects you can use the .inserted_id and .inserted_ids properties respectively to get the inserted object ids.
See this link for more info on insert_one and insert_many and this link for more info on pymongo.results.InsertOneResult.
updated; removed previous because it wasn't correct
It looks like you can also do it with db.notes.save(...), which returns the _id after it performs the insert.
See for more info:
http://api.mongodb.org/python/current/api/pymongo/collection.html
some_var = db.notes.insert({ title: "title", details: "note details"})
print(some_var.inserted_id)
You just need to assigne it to some variable:
someVar = db.notes.insert({ title: "title", details: "note details"})
To get the ID after an Insert in Python, just do like this:
doc = db.notes.insert({ title: "title", details: "note details"})
return str(doc.inserted_id) # This is to convert the ObjectID (type of doc.inserted_id into string)

Getting distinct SelectListItem

I am using Linq to get only unique member of a select List item. How do I return a this list...
What I have now is
var queryResult = PatientList.Select(c => c).Distinct();
PatientList = (List<SelectListItem>)queryResult;
I am getting a cast error on the second line. What should an enterprising young developer do?
Try
PatientList = queryResult.ToList();
You version uses casting, which is impossible in this case, as the query result is not a list. ToList constructs a new list, basing on the enumerable against which it is called. It does something like this:
public static List<T> ToList<T>(this IEnumerable<T> collection)
{
return new List<T>(collection);
}
You must be sure, obviously, that PatientList elements are of type SelectListItem and be aware that Distinct() will return the different OBJECTS, but not items with different fields. I.e., if in PatientList you have two independently constructed items with equal Selected, Text and Value properties, you will still have two as a result of the Distinct() call.
Additionally, what is the reason to use Select(c => c)? It effectively does noting.
I don’t know what type are the item in your list but for what you have posted you can call Distinct() directly on the list
List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };
IEnumerable<int> distinctAges = ages.Distinct();
Adding .ToList() if you need to convert it to a List