field declaration
price=fields.Integer(string="Price")
service_date=fields.Date(string="Last servicing date")
service_charge=fields.Integer(string="Last Service Charge")
total_charge=fields.Integer(string="Total Spent")
onchange Function in which servie_date is used as argument
#api.onchange('service_date')
def _onchange_total_charge(self):
if self.total_charge > 0:
self.total_charge+=self.service_charge
else:
self.total_charge=self.price+self.service_charge
#api.onchange('service_date')
#api.depends('service_date')
def _onchange_total_charge(self):
if self.total_charge > 0:
self.total_charge += self.service_charge
else:
self.total_charge = self.price + self.service_charge
Try to re-write the code like this
I've used your code it works on my odoo instance. Please make sure that you call the same in field in your xml file. you can also use compute field to get your calculation done.
Related
I'm trying to print the result according to the user's age selection in the form, but my if,elif and else statements are not working.
class Quiz(models.Model):
age_choices = (('10-12', '10-12'),
('13-16', '13-16'),
('17-20', '17-20'),
('21-23','21-23'),
)
age = models.CharField(max_length = 100, choices = age_choices)
views.py
def create_order(request):
form = QuizForm(request.POST or None)
if request.method == 'POST':
quiz = Quiz.objects
if quiz.age=='10-12':
print("10-12")
elif quiz.age=='13-16':
print("13-16")
elif quiz.age=='17-20':
print("17-20")
elif quiz.age=='21-23':
print("21-23")
else:
return None
context = {'form':form}
return render(request, "manualupload.html", context)
quiz = Quiz.objects will return a django.db.models.manager.Manager object and this can be further used to fetch the objects from database belonging to that particular model. The appropriate query set will be quiz = Quiz.objects.all() Then you will get the list of all objects in that belong to Quiz model. Once you get list of all objects, you can get the specific object either by indexing or by filtering using a specific query that you need to look into and then for that particular object you can get the age property.
Refer to official django documentation about creating queries for more information.
As #Abhijeetk431 mentioned, your issue lies in quiz = Quiz.objects.
If you use type(quiz), you will find that it outputs django.db.models.manager.Manager. This is not what you want, as age is a property of the Quiz class, not the Manager class.
For starters, refer to this.
This will return you a Queryset list, something akin to an Excel table. age is akin to the column in the table. To get age, what you want is the row (the actual Quiz object) in said table, which you can achieve using get or using the square brackets [].
Thus, your code should look something like this:
Model.objects.all()[0]
That would return the correct object(only the first row) and allow you to get the column value.
However, further clarification will be needed though, to know exactly what your problem is aside from 'it doesn't work'. How did you know your code is not working; what did the debugger tell you?
I'm trying to take an object, look up a queryset, find the item in that queryset, and find the next one.
#property
def next_object_url(self):
contacts = Model.objects.filter(owner=self.owner).order_by('-date')
place_in_query = list(contacts.values_list('id', flat=True)).index(self.id)
next_contact = contacts[place_in_query + 1]
When I add this to the model and run it, here's what I get for each variable for one instance.
CURRENT = Current Object
NEXT = Next Object
contacts.count = 1114
self.id = 3533 #This is CURRENT.id
place_in_query = 36
contacts[place_in_query] = NEXT
next_contact = CURRENT
What am i missing / what dumb mistake am i making?
In your function, contacts is a QuerySet. The actual objets are not fetched in the line:
contacts = Model.objects.filter(owner=self.owner).order_by('-date')
because you don’t use a function like list(), you don’t iterate the QuerySet yet... It is evaluated later. This is probably the reason of your problem.
Since you need to search an ID in the list of contacts and the find the next object in that list, I think there is no way but fetch all the contact and use a classic Python loop to find yours objects.
#property
def next_object_url(self):
contacts = list(Model.objects.filter(owner=self.owner).order_by('-date').all())
for curr_contact, next_contact in zip(contacts[:-1], contacts[1:]):
if curr_contact.id == self.id:
return next_contact
else:
# not found
raise ContactNotFoundError(self.id)
Another solution would be to change your database model in order to add a notion of previous/next contact at database level…
(Django 2.0, Python 3.6, Django Rest Framework 3.8)
I'm trying to override Django's save() method to post multiple instances when a single instance is created. I have a loop that changes the unique_id which I have saved as a randomly generated string, and the datetime value which is updated through another function called onDay().
My thinking was, that if I changed the unique_id each time I looped around, Django would save the instance as a new instance in the database. But, I keep getting back an infinite recursion error when I run it though. When I checked it with pdb.set_trace(), everything does what it's supposed to until I hit the save() value in the for loop. Once that happens, I just get taken back to the line if self.recurrent_type == "WEEKLY":.
I've used super() in a similar way (without looping) to override the save() function for a separate model, and it worked as expected. I think there's just something I'm misunderstanding about the super() function.
Here is what I have so far:
Overriding save()
def save(self, *args, **kwargs):
if not self.pk: # if there is not yet a pk for it
# import pdb; pdb.set_trace()
if self.recurrent_type == "WEEKLY":
LIST_OF_DAYS = self.days_if_recurring["days"]
HOW_MANY_DAYS_FOR_ONE_WEEK = len(LIST_OF_DAYS)
REPEATS = HOW_MANY_DAYS_FOR_ONE_WEEK * self.number_of_times_recurring
RESET_COUNTER = 0
for i in range(REPEATS):
self.id = ''.join(random.choices(string.ascii_letters, k=30))
self.calendarydays = onDay(self.calendarydays, LIST_OF_DAYS[RESET_COUNTER])
if RESET_COUNTER == HOW_MANY_DAYS_FOR_ONE_WEEK - 1:
RESET_COUNTER = 0
self.save()
else:
self.id = ''.join(random.choices(string.ascii_letters, k=30))
self.save()
return super(Bookings, self).save(*args, **kwargs)
onDay()
def onDay(date, day): # this function finds next day of week, and skips ahead one week if today's time has already passed
utc = pytz.UTC
check_right_now = utc.localize(datetime.datetime.now())
if check_right_now > date:
forward_day = date + datetime.timedelta(days=(day - date.weekday() + 7) % 7) + datetime.timedelta(days=7)
else:
forward_day = date + datetime.timedelta(days=(day - date.weekday() + 7) % 7)
return forward_day
As always, any help is greatly appreciated.
You should call super(Bookings, self).save(*args, **kwargs) instead of self.save(). The super save will call django's actual model save which is what you want. Calling self.save() will just call your overridden save which doesn't do anything in the database. But yeah what #AamirAdnan said should fix your problem.
I would like to do this:
def retrieve_data(self, variable):
start_date = datetime.date.today() - datetime.timedelta(int(self.kwargs['days']))
invoice_set = InvoiceRecord.objects.filter(sale_date__gte=start_date)
total = 0
for invoice in invoice_set:
for sale in invoice.salesrecord_set.all():
total += getattr(self, variable)
return round(total)
Where variable is submitted as a string that represents one of my model methods:
#property
def total_sale(self):
return self.sales_price * self.sales_qty
But my effort doesn't work:
def total_sales(self):
return self.retrieve_data(variable="total_sale")
It simply says:
'SalesSummaryView' object has no attribute 'total_sale'
Evidently, I am misunderstanding the usage. Can someone help me figure out a way to accomplish this goal?
Got it! I was calling getattr() on the view, rather than the model. Instead of using self, I needed to submit the sale object.
for invoice in invoice_set:
for sale in invoice.salesrecord_set.all():
total += getattr(sale, variable)
I'm trying to make an appraisal system
This is my class
class Goal(db.Expando):
GID = db.IntegerProperty(required=True)
description = db.TextProperty(required=True)
time = db.FloatProperty(required=True)
weight = db.IntegerProperty(required=True)
Emp = db.UserProperty(auto_current_user=True)
Status = db.BooleanProperty(default=False)
Following things are given by employee,
class SubmitGoal(webapp.RequestHandler):
def post(self):
dtw = simplejson.loads(self.request.body)
try:
maxid = Goal.all().order("-GID").get().GID + 1
except:
maxid = 1
try:
g = Goal(GID=maxid, description=dtw[0], time=float(dtw[1]), weight=int(dtw[2]))
g.put()
self.response.out.write(simplejson.dumps("Submitted"))
except:
self.response.out.write(simplejson.dumps("Error"))
Now, here Manager checks the goals and approve it or not.. if approved then status will be stored as true in datastore else false
idsta = simplejson.loads(self.request.body)
try:
g = db.Query(Goal).filter("GID =", int(idsta[0])).get()
if g:
if idsta[1]:
g.Status=True
try:
del g.Comments
except:
None
else:
g.Status=False
g.Comments=idsta[2]
db.put(g)
self.response.out.write(simplejson.dumps("Submitted"))
except:
self.response.out.write(simplejson.dumps("Error"))
Now, this is where im stuck..."filter('status=',True)".. this is returning all the entities which has status true.. means which are approved.. i want those entities which are approved AND which have not been assessed by employee yet..
def get(self):
t = []
for g in Goal.all().filter("Status = ",True):
t.append([g.GID, g.description, g.time, g.weight, g.Emp])
self.response.out.write(simplejson.dumps(t))
def post(self):
idasm = simplejson.loads(self.request.body)
try:
g = db.Query(Goal).filter("GID =", int(idasm[0])).get()
if g:
g.AsmEmp=idasm[1]
db.put(g)
self.response.out.write(simplejson.dumps("Submitted"))
except:
self.response.out.write(simplejson.dumps("Error"))
How am I supposed to do this? as I know that if I add another filter like "filter('AsmEmp =', not None)" this will only return those entities which have the AsmEmp attribute what I need is vice versa.
You explicitly can't do this. As the documentation states:
It is not possible to query for entities that are missing a given property.
Instead, create a property for is_assessed which defaults to False, and query on that.
could you not simply add another field for when employee_assessed = db.user...
and only populate this at the time when it is assessed?
The records do not lack the attribute in the datastore, it's simply set to None. You can query for those records with Goal.all().filter('status =', True).filter('AsmEmp =', None).
A few incidental suggestions about your code:
'Status' is a rather unintuitive name for a boolean.
It's generally good Python style to begin properties and attributes with a lower-case letter.
You shouldn't iterate over a query directly. This fetches results in batches, and is much less efficient than doing an explicit fetch. Instead, fetch the number of results you need with .fetch(n).
A try/except with no exception class specified and no action taken when an exception occurs is a very bad idea, and can mask a wide variety of issues.
Edit: I didn't notice that you were using an Expando - in which case #Daniel's answer is correct. There doesn't seem to be any good reason to use Expando here, though. Adding the property to the model (and updating existing entities) would be the easiest solution here.