django 1.5 Get latest records by Date - database

I want to get all the records that have the latest date.
class Report(models.Model):
id = models.AutoField(primary_key=True)
part = models.ForeignKey(Part,related_name="reports")
this_week_use = models.IntegerField(blank=True,null=True,default=0)
this_week_fail = models.IntegerField(blank=True,null=True,default=0)
this_week_fail_percent = models.DecimalField(max_digits=5,decimal_places=2,blank=True,null=True,default=0.00)
prev4_week_use = models.IntegerField(blank=True,null=True,default=0)
prev4_week_fail = models.IntegerField(blank=True,null=True,default=0)
prev4_week_fail_percent = models.DecimalField(max_digits=5,decimal_places=2,blank=True,null=True,default=0.00)
platform = models.ForeignKey(Platform,related_name="reports")
date = models.DateField(auto_now_add=True)
class Meta:
unique_together = ('part','platform','date')
I tried
rows = Report.objects.annotate(max_date=Max('date').filter(date=max_date))
Which resulted in no data

Use latest() method
Report.objects.latest('date')

You can use order_by, it's available in 1.5:
latest_rows = Report.objects.all().order_by('-date')
If you want any query in Your report model, by default ordered by this date field, then you can add this ordering on the meta section of your Report model.
class Report(models.Model):
class Meta:
ordering = '-date'
Now you can make query without using order_by in your query, but with same result:
latest_rows = Report.objects.all()

If you don't mind to make two queries, this should do it:
max_date = Report.objects.latest('date').date
qs = Report.objects.filter(date=max_date)

Related

How can update field by overriding save method which is in another app models

I have two models Bill and Payment each with 3 fields. Here I want to update field last_price directly when user pay bill. If user pay complete amount then it would be 0. or if user not pay complete amount then remaining amount want to be save in last_price. So here I want to update amount of last_bill directly when user pay bill.
Note: Both models are in separate app
My Fields are:
BillApp/models
Bill(model.Model):
bill_no = models.IntegerField(max_length = 100,primary_key=True)
last_price = models.IntegerField()
Name = models.CharField(max_length = 20)
PaymentApp/models
Payment(model.Model):
id = models.CharField(max_length = 100,primary_key=True)
bill_no = models.ForeignKey(Bill, on_delete = SET_NULL,null=True)
total_amount = models.CharField(max_length = 10)
def save(...):
Update value of Bill.last_price
How do I update value of Bill.last_price in the save method
I tried this for update field last_price
def save(self,*args, **kwargs):
new_last_price = self.total_amount - self.bill_no.last_price
print("new_last_price : ",new_last_price)
bill_detail = Bill.objects.filter(bill_no=self.bill_no).first()
print("bill_detail : ",bill_detail)
try:
with transaction.atomic():
updated_field = bill_detail.save(update_fields = ['last_price'])
print("updated_field : ", updated_field)
super().save(*args, **kwargs)
print(Bill.objects.filter(bill_no=self.bill_no).first().last_price)
except IntegrityError:
print('Exception in save')
I getting correct output of new_last_price and bill_detail..
but updated_field display None ..
How Can I save new value in Bill?
Your save method will save the data and refresh the object instance but will not return the object instance. Use directly show last price.
bill_detail.save(update_fields = ['last_price'])
print(bill_detail.last_price)

How to order by nested objects fields?

I have some classes
class MarketProduct(models.Model, ObjectMarket):
_state_class = 'MarketProductState'
uuid = models.UUIDField(u'Код',
default=uuid.uuid4, editable=False)
name = models.CharField(u'Название',
max_length=255, db_index=True)
class MarketItem(models.Model, ObjectMarket):
_state_class = 'MarketItemState'
STOCK, AUCTION = 1, 2
ITEM_CHOICES = (
(STOCK, u'Сток'),
(AUCTION, u'Аукцион'),
)
product = models.ForeignKey(MarketProduct)
start_at = models.DateTimeField(u'Начало продажи')
I want to get MarketItemViewSet and use
filter_backends = (filters.OrderingFilter,`)
I send request with filed orderby by angular.
If I send orderby = start_at, all are good, but I want to send
orderby = product.id, it doesn't work.
You can try specifying product__id to perform ordering based on the id of product.
orderby = product__id
Specify ordering_fields in your viewset.
ordering_fields = ('product__id', )
As you are using django-rest-framework you have to use ordering_fields as you can see from the documentation here.Hope it helps example:
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('username', 'email')
ordering = ('created_on') # for reverse ordering = ('-created_on')
If an ordering attribute is set on the view, this will be used as the default ordering.
Typically you'd instead control this by setting order_by on the initial queryset, but using the ordering parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template

The best way to store data or query data on google app engine

I want to be able to store some data in app engine and I am looking for some help on the best way to store the data or retrieve the data through a query. I have a list of users and want them to be able to add cars they want to sell and enter a lower and upper limit they would accept. When a user is searching for a car and enters a price, if this price is between the lower and upper limits, it will return the car:
class User(ndb.Model):
username = ndb.StringProperty()
cars = ndb.StructuredProperty(Car, repeated = True)
datecreated = ndb.DateTimeProperty(auto_now_add = True)
date_last_modified = ndb.DateTimeProperty(auto_now = True)
class Car(ndb.Model):
lowerprice = ndb.IntegerProperty()
maxprice = ndb.IntegerProperty()
make = ndb.StringProperty()
model = ndb.StringProperty()
datecreated = ndb.DateTimeProperty(auto_now_add = True)
date_last_modified = ndb.DateTimeProperty(auto_now = True)
I can't filter on:
c = User.query(User.car.lowerprice >= int(self.carprice), User.car.maxprice < int(self.carprice)).get())
As it returns BadRequestError: Only one inequality filter per query is supported.
Should I structure or store the data differently to allow filtering on one inequality or should I try and use and and / or query?
Is there anything else you would recommend?
Try something like this:
holder = User.query(User.car.lowerprice >= int(self.carprice)).get())
results = filter(lambda x: x.car.maxprice < int(self.carprice), holder)
It boils down to having to programmably handling the second filter.

Query for repeated ndb.KeyProperty not working

What's wrong with my query?
Here are my models:
class Positions(ndb.Model):
title = ndb.StringProperty(indexed=True)
summary = ndb.TextProperty()
duties = ndb.TextProperty()
dateCreated = ndb.DateTimeProperty(auto_now_add=True)
dateUpdated = ndb.DateTimeProperty(auto_now=True)
class Applicants(ndb.Model):
name = ndb.StringProperty(indexed=True)
position = ndb.KeyProperty(kind=Positions,repeated=True)
file = ndb.BlobKeyProperty()
dateCreated = ndb.DateTimeProperty(auto_now_add=True)
dateUpdated = ndb.DateTimeProperty(auto_now=True)
Here is my query:
class AdminPositionInfoHandler(BaseHandler):
def get(self,positionKeyId):
user = users.get_current_user()
if users.is_current_user_admin():
positionKey = ndb.Key('Positions',int(positionKeyId))
position = positionKey.get()
applicants = Applicants.query(position=position.key).fetch() # the query
values = {
'position': position,
'applicants': applicants,
}
self.render_html('admin-position-info.html',values)
else:
self.redirect(users.create_login_url(self.request.uri))
What seems to be wrong in using the query:
applicants = Applicants.query(position=position.key).fetch()
I got this error:
File "C:\xampp\htdocs\angelstouch\main.py", line 212, in get
applicants = Applicants.query(position=position.key).fetch()
...
TypeError: __init__() got an unexpected keyword argument 'position'
I also tried using positionKey instead of position.key:
applicants = Applicants.query(position=positionKey).fetch()
I got this from "Ancestor Queries" section of GAE site:
https://developers.google.com/appengine/docs/python/ndb/queries
You don't pass arguments to query like that - ndb uses overridden equality/inequality operators, so you can express queries more 'naturally', with '==', '<', '>' etc., so:
applicants = Applicants.query(Applications.position==position.key).fetch()
The section in the on Filtering by Property Values gives some more examples.
(ancestor is a special-case for queries - it isn't a model property)

Django - filter by foreign key string

main table:
class example(models.Model):
name = models.CharField('Item Name', max_length=200)
color = models.ManyToManyField(Color)
category = models.ForeignKey(Category)
image = models.ImageField('Item Image',upload_to="example/images/")
Category table:
class Category(models.Model):
catname = models.CharField('Category Name',max_length=100)
How can i query it while filtering the example table according to the category.
This didn't work out:
def list(request, cat):
c = example.object.filter(category = cat)
What should i change to make this filtering work ?
See Django's documentation on related lookups:
def list(request, cat):
c = example.objects.filter(category__catname=cat)

Resources