How to get time stamp of database update using psycopg2 - django

I am implementing HTTP streaming with Django. When a user opens a webpage, there is a connection made to the server which returns back data when a new entry is made to the postgresql table.
Let's call the model "M", the model which when updated returns back the data to the client
I have a view get_update which does the timestamp checking and returns back data.
How can I go about doing it?

Without seeing your code it's hard to know, but from what I understand you're trying to query the last time a table was updated. If that's correct, I would just add a "last_updated" attribute on your model and query that, like so:
models.py
class YourModel(models.Model):
last_updated = models.DateTimeField(auto_now=True)
views.py
def get_update():
time_updated = YourModel.objects.last().last_updated
return(time_updated)

Related

TimeField returning None in Django

I have an existing database I need to pull data from the timestamp field in Django. I created the Django model as a TimeField, but when I query the data I get 'None' instead of the data in the timestamp field.
From my model class: (there is more in the model, I just condensed this for readability)
class Report(models.Model):
upload_time = models.TimeField()
date = models.CharField(max_length=9)
#staticmethod
def get_reports(**query):
reports = Report.objects.order_by('date').filter(query)
for report in reports:
print(report.upload_time)
In my views.py I have a method that checks for the date I am looking for to pull all reports from that date. The database saved the date as a string, so I get that ok, then just turn it into a datetime object and call my get_reports method by passing the date into it. It works to get everything from the report except the timestamp.
What am I missing?

Django Rest framework + EmberJS File upload update(patch)

I have a model like this:
// models.py
class MyModel(models.Model):
name = models.CharField(max_length=30, null=True, blank=True)
someboolean = models.BooleanField(default=False)
someotherBoolean = models.BooleanField(default=False)
myfilefield = models.FileField(upload_to='/files/')
Then i have a serializer like this:
// serializers.py
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
Then i have a View which inherit from RetrieveUpdateDestroyAPIView
This Django Rest setup is connected to the EmberJS and is running ok. The data from the server is retrived without any problem and the myfilefield content is represented like a string in ember which is a url to the actual file. When i think of uploading a file to the field on the Django Rest side it seems that i have to play a little with FileUploadParser to make it right and i think this is not much more lines of code into it.
But the issue is that my model on the Ember side should be updated in parts. Sometimes i need to update only the value of someboolean and do not send any files to myfilefield either because the file is already there or because this is done in the other UI iteration (separately). When in Ember i call this.get('model').save(); after some change to the someboolean is made it sends the whole model data back to django rest and the myfilefield in this json request is represented as a string and not as file thus the server returns an error.
As i understand there could be some workarounds to this situation:
The first would be to create custom serializers.CustomFileField which checks whether the provided string is equal to the url which is generated by the serializer on the output and if it is just leaves the file intact.
Second option would be to somehow implement the quick and dirty patch on the ember side which as i understand is still thing under development according to This Link. But this option seems to be quite hard as i have a lot of models with filefields and i should implement the patch method in ember for each and every one of them.
The third option as i forsee would be to create a special File model like so:
//models.py
class File(models.Model):
filebody = models.FileField(upload_to='/files/')
and make the myfilefield on the MyModel read_only so it won't validate at any time. I could also implement some method on the File model which would recieve the model and instance for which this file really belongs and after upload and validation would make the myfilefield = filebody
This method also seems very dirty but at least keeps some concepts abstracts so i wouldn't need to worry how many models with FileFields i actually have in my project.
My UI expects the user to do the change to one model field at a time and then save the model - i.e.
1. change the name field, save the model.
2. change the boolean field, save the model.
3. upload file, save the model.
Any suggestions on what would be the best way in terms of django rest to accomplish this considering the fact that ember still does not support PATCH requests.

Why does Django set the pk of all my models to '90'?

I'm running Django 1.5 with SQLite, and I have a model called Assignment. Whenever I create one, it gets created with the correct pk value. But, whenever I try to retrieve any Assignment from my database, it is always returned with a pk of 90. I've been fighting this for an hour, and I have to admit I'm completely confused.
Here's my code, if it's any use.
class Assignment(models.Model):
class Meta:
app_label = 'holiday'
unique_together = ('year', 'employee')
year = models.PositiveIntegerField(db_index=True)
employee = models.ForeignKey('bsc.Employee', db_index=True)
days = models.PositiveIntegerField(null=True)
This, and a bunch of methods that calculate some values based on models related to this one. Nothing fancy.
I've got to add that this model has had a somewhat rough past - with all my absent-mindedness, I had originally set year as the primary key, which quickly failed as soon as I added two Assignments to different employees. Maybe I should look at the DB schema and see if anything's wrong. Thankfully, the app hasn't made it to production yet, but hopefully this can be fixed without a full DB reset.
If you had created 90 previous records then deleted the rows from your database; your database key index will still be set to what would have been the next primary key number in your database.
The way to resolve this would be to as described in this other stackoverflow post:
SQLite Reset Primary Key Field

Refreshing a model's unmanaged related model in Django

I have a model (lets call it Entity) that has an attribute (Attribute) that changes over time, but I want to keep a history of how that attribute changes in the database. I need to be able to filter my Entities by the current value of Attribute in its manager. But because Django (as far as I can tell) won't let me do this in one query natively, I have created a database view that produces the latest value of Attribute for every Entity. So my model structure looks something like this:
class Entity(models.Model):
def set_attribute(self, value):
self.attribute_history.create(value=value)
def is_attribute_positive(self, value):
return self.attribute.value > 0
class AttributeEntry(models.Model):
entity = models.ForeignKey(Entity, related_name='attribute_history')
value = models.IntegerField()
time = models.DateTimeField(auto_now_add=True)
class AttributeView(models.Model)
id = models.IntegerField(primary_key=True, db_column='id',
on_delete=models.DO_NOTHING)
entity = models.OneToOneField(Entity, related_name='attribute')
value = models.IntegerField()
time = models.DateTimeField()
class Meta:
managed = False
My database has the view that produces the current attribute, created with SQL like this:
CREATE VIEW myapp_attributeview AS
SELECT h1.*
FROM myapp_attributehistory h1
LEFT OUTER JOIN myapp_attributehistory h2
ON h1.entity_id = h2.entity_id
AND (h1.time < h2.time
OR h1.time = h2.time
AND h1.id < h2.id)
WHERE h2.id IS NULL;
My problem is that if I set the attribute on a model object using set_attribute() checking it with is_attribute_positive() doesn't always work, because Django may be caching that the related AttributeView object. How I can I make Django update its model, at the very least by requerying the view? Can I mark the attribute property as dirty somehow?
PS: the whole reason I'm doing this is so I can do things like Entity.objects.filter(attribute__value__exact=...).filter(...), so if someone knows an easier way to get that functionality, such an answer will be accepted, too!
I understand that the attribute value is modified by another process (maybe not even Django) accessing the same database. If this is not the case you should take a look at django-reversion.
On the other hand if that is the case, you should take a look at second answer of this. It says that commiting transaction invalidate query cache and offer this snippet.
>>> from django.db import transaction
>>> transaction.enter_transaction_management()
>>> transaction.commit() # Whenever you want to see new data
I never directly solved the problem, but I was able to sidestep it by changing is_attribute_positiive() to directly query the database table, instead of the view.
def is_attribute_positive(self, value):
return self.attribute_history.latest().value > 0
So while the view gives me the flexibility of being able to filter queries on Entity, it seems the best thing to do once the object is received is to operate directly on the table-backed model.

Django reading old model?

I changed the model, synced the db, and now when i do:
Prs = Products.objects.filter(PrName__icontains='bla')
I get the error:
ERROR: column search_products.pr_name does not exist
LINE 1: SELECT "search_products"."id", "search_products"."pr_name", ...
But pr_name was the old model, this is how the new model looks like:
class Products(models.Model):
PrName = models.CharField(max_length=255)
PrDescription = models.CharField(max_length=4000)
PrPrice = models.DecimalField(max_digits=5, decimal_places=2)
PrCompany = models.ForeignKey(Companies)
def __str__(self):
return self.PrName
Why am i getting this error? I synced the db 100 times, checked all the code, there is no reference to pr_name anywhere?
Have you tried restarting your server? If you are using anything other than the development server, you'll probably need to do that manually after making changes like this.
Unfortunately the thing you try to do is not supported by django out of the box :-(
but you can do it ether by adding a db_column to the fields or by exporting the data, removing the table from the database, edit the export file, recreate the database table and reimporting the data.
Also look at the various schema evolution solutions out there