How can I get a list from model for the template - django

in the models.py, I have a model which has a list attribute:
Class Controller(models.Model):
def controller(self):
result = []
#...do some works here...
result = xxx
Now I want to use the "result" attribute in the template, in views.py I have:
def results(request):
cmodel = Controller()
cmodel.controller()
firstList = get_list_or_404(Controller, 'I am not sure how to write this filter')
return render_to_response('blablabla/')
I am not sure how to write the filter, since the samples are giving something like "pk=1", but I don't have any primary keys or ids for the 'result' object. Can anyone help me? Thank you.

Your controller function should return result:
Class Controller(models.Model):
def controller(self):
result = []
#...do some works here...
result = xxx
return result # <----------
And then you can get it as:
c = Controller()
result_list = c.controller()
Is that what you want?

Related

Django Retrive data after a specific number or index

i have two rendered contexts in my view:
def PostHomeView(request):
RecentPost = Post.objects.order_by("-date").all()[:5]
AllOtherPosts = Post.objects.order_by("-date").all()
template_name = 'lista_post.html'
context = {**strong text**
'recentposts' : RecentPost,
'allposts' : AllOtherPosts
}
return render(request,template_name,context)
in the second one ('allposts') i would like to get all objcects without the first fve
how can i do it?
Use slicing as AllOtherPosts = Post.objects.order_by("-date").all()[5:]

Call method on Django fields

class Colour(models):
...
def colour_preview(self):
return format_html(...)
class ColourTheme(models):
colour1 = models.ForeignKey(Colour)
colour2 = models.ForeignKey(Colour)
colour3 = models.ForeignKey(Colour)
...
def preview(self):
for field in self._meta.get_fields(include_parents=False):
if (field.related_model == Colour):
field.colour_preview()
I have a ColourTheme model with multiple Colour foreign keys, and I want to call a function on each of the Colour objects referred to by those fields. The last line of code above fails. I would like to call colour_preview on all Colour fields without hardcoding them (self.colour1.colour_preview() works but not ideal).
How might I achieve this?
You cannot refer to the field in order to access related object method.
Try something like this (I haven't tested it):
class ColourTheme(models):
colour1 = models.ForeignKey(Colour)
colour2 = models.ForeignKey(Colour)
colour3 = models.ForeignKey(Colour)
...
def preview(self):
for field in self._meta.get_fields(include_parents=False):
if (field.related_model == Colour):
field_obj = field.value_from_obj(self) # To get obj reference
field_obj.colour_preview()

How to execute a function when a variable's value is changed?

In Odoo 10, I want to change the value of a variable when the forecasted quantity of a product is changed. I tried using the #api.onchange decorator, but it doesn't work. The forecasted quantity change, but the variable keeps the same value. I have this:
class MyProduct(models.Model):
_inherit = 'product.product'
was_changed = fields.Boolean(default = False)
#api.onchange('virtual_available')
def qtychanged(self):
self.was_changed = True
_logger.info('Product_Qty_Cahnged: %s',str(self.virtual_available))
In this code, if the forecasted quantity of a product would change, the variable was_changed should be set to True, but nothing happens.
After that, I tried to overwrite the write method for my custom class, like this:
class MyProduct(models.Model):
_inherit = 'product.product'
was_changed = fields.Boolean(default=False)
#api.multi
def write(self, values):
if values['virtual_available']:
values['was_changed'] = True
# THE FOLLOWING LINES WERE IN THE ORIGINAL WRITE METHOD
res = super(MyProduct, self).write(values)
if 'standard_price' in values:
self._set_standard_price(values['standard_price'])
return res
But still, I have the same result. I can't seem to get that flag to change. So, any ideas?
Try this:
class MyProduct(models.Model):
_inherit = 'product.product'
was_changed = fields.Boolean(default = False)
#api.onchange('virtual_available')
def qtychanged(self):
self.write({'was_changed': True})
_logger.info('Product_Qty_Cahnged: %s',str(self.virtual_available))

How to get one query from two models?

I have two models:
class ModManager(models.Manager):
def myfilter(self, options = dict()):
if options.has_key('not_image'):
kwargs['image__isnull'] = False
return self.filter(**kwargs)
class Model_1(models.Model):
...
objects = MyManager()
class Model_2(models.Model):
something = models.ForeignKey(Model_1)
something_else = ...
...
How to get all data from Model_2 related to Model_1 in MyManager? I want to get one query. I have so far:
in Model_1:
def get_model_2(self):
self.model_2_objs = self.model_2_set.all()
But it generates many queries when I calling get_model_2 function.

filter using Q object with dynamic from user?

In my views.py I have a method:
#......
def get_filter_result(self, customer_type, tag_selected):
list_customer_filter=[]
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
for customer_filter in customers_filter:
customer_filter.list_authorize_sale_type = sale_type_selected(customer_filter.authorize_sale_type)
list_customer_filter.append(customer_filter)
return list_customer_filter
**My case tag_selected is the checkbox values that user checked
I have a problems with tag_selected(is the list=1,2,3,...) that pass from my url
/?customer_type=TDO&tag=2 ===>filter okay
/?customer_type=TDO&tag=3 ===>filter okay
?customer_type=TDO&tag=2,3 ===>How Can I add And condition in filter?
for example
if len(tag_selected)==1:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
else:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected[0])
Q(tag__id=tag_selected[1])
Q(tag__id=tag_selected[2])
...
)
This works for both single and multiple conditions:
idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)