I'm have a django app with the following model.
class Posts(models.Model):
post = models.TextField(max_length=1500)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
likes = models.ManyToManyField(User, related_name="post_likes")
category = models.CharField(max_length=50, default=None)
To allow the users search for a particular blog and then display those objects I have the following view.
def index(request):
if request.method == "GET":
search = request.GET.get("input")
posts = Posts.objects.filter(category__icontains=f"{search}")
else:
posts = Posts.objects.all()
params = {'blog': posts}
return render(request, 'index.html', params)
In the above view , variable search contains what user has searched for, that I'm receiving through a form.
But I also want to provide a sort functionality after user has searched for a blog. Like user searches for "recipes", I need to show them all the search results and then let him sort them based on likes and recent etc. How do I do it since I'm losing search terms just after displaying the results.
I'm assuming the sort options are also part of the search form so you could also send the chosen sort option as a query parameter to the backend, just as you're doing with the search term:
sort = request.GET.get('sort')
# use the sort options to order your queryset as you desire
Related
I'm trying to understand how can I define model as a class containing 2 integers and 1 charfield and then make it a part of another model.
Example of data I need
I guess in object oriented programming I should define model class like this:
class Component(models.Model):
pipe_type = models.CharField(max_length=200)
length = models.IntegerField()
amount = models.IntegerField()
And then I don't know how can I use it with django models, it should be something like this:
class Item(models.Model):
name = models.CharField()
components_needed = ? LIST OF Component class ?
Also, since components needed size will wary for objects, it should be possible to extend it's size with button on a page, for example there could be 3 input fields and next to them would be "+" and "-" button to add/remove another set of 3 input fields
I spent entire day looking for solution, but at this point I'm not sure if django can handle this. I'm new to python and django, so there are many things I do not understand.
I will be grateful for any kind of help
the only way now( you canot put multi FK in one cell) is like django itself using with user/groups so you need 3 models.
in django there is group, user and user_group so i suggesting for you:
class Component(models.Model):
pipe_type = models.CharField(max_length=200)
length = models.IntegerField()
amount = models.IntegerField()
class Item(models.Model):
name = models.CharField()
class Item_Component(models.Model):
Component = models.ForeignKey(Component, on_delete=models.CASCADE)
Item = models.ForeignKey(Item, on_delete=models.CASCADE)
so now in third model you can have multiple rows with item and with diffrent component.
open yours db viewer app and see django user_group table.
I am looking for a way to retrieve a parent field during a query of the the children records. At this time I have the following example model.
class Record(models.Model):
event_title=models.CharField(max_length=500)
event_description=models.CharField(max_length=4000)
class SecondTable(models.Model):
event_code=models.ForeignKey(Record, default=0, on_delete=models.CASCADE)
wasfun=models.BoolField(default=True)
When I view the values of the queryset and select_related below, the values from the parent don't seem to be included (i.e. event_description). However, the .query property shows all the fields being selected.
SecondTable.objects.all().select_related("event_code").values()
Is there a way to see all values from the joined tables? Sorry for a newbie question. Thanks!
I think not in only one line, but you can try with next:
values_second_table = [s.name for s in SecondTable._meta.fields]
values_first_table = ['event_code__{}'.format(r.name) for r in Record._meta.fields]
my_values = values_second_table + values_first_table
SecondTable.objects.all().select_related("event_code").values(*my_values)
I am slowly progressing in my django journey, but this one has me stumped. I am trying to populate a CreateView with a different model via a copy command using the get_initial override. All of the attributes copy as I would expect with the exception of the ManytoMany fields. I've researched this topic most of today, and found the following which is very close to what I'm trying to figure out KeyError: 'manager' in django get_initial.
My View...
class BookView(LoginRequiredMixin,CreateView):
model = Book
template_name = 'book/titles.html'
form_class = BookForm
def get_initial(self):
initial = super(BookView, self).get_initial()
author = author.objects.get(pk=self.kwargs["pk"])
initial = author.__dict__.copy()
initial.update({
"author": author.name,
}}
for field in self.form_class.base_fields.items():
value = getattr(self.get_object(), field)
if field == 'author':
value = self.get_object().author.all()
initial.update({field: value})
return initial
I incorporated the suggested change based on the issue that I found on SO, but I still am getting a 'manager" KeyError. I am ultimately trying to populate the manytomanyfield in my model and then save the values, but to no avail. Any suggests are appreciated!
What a difference a day makes....
def get_initial(self):
initial = super(BookView, self).get_initial()
author = author.objects.get(pk=self.kwargs["pk"])
initial = author.__dict__.copy()
initial.update({
"author": author.name.all(),
}}
return initial
I added a .all() after the reference to the manytomanyfield in my initial get and also update the form to get the field in question. Much cleaner than a few hacks I kinda got working along the way.
I cannot understand where stored keywords and urls.
For example in module website exist class website_seo_metadata. It has such columns:
'website_meta_title': fields.char("Website meta title", translate=True),
'website_meta_description': fields.text("Website meta description", translate=True),
'website_meta_keywords': fields.char("Website meta keywords", translate=True),
When I added some keywords for page records not exist in DB.
I can not understand where stored urls for pages. I know, if I create route:
#http.route('/contacts/', type='http', auth="public", website=True)
this path was added to sitemap.xml
For generate sitemap.xml used sitemap_xml_index method:
#http.route('/sitemap.xml', type='http', auth="public", website=True)
def sitemap_xml_index(self):
current_website = request.website
cr, uid, context = request.cr, openerp.SUPERUSER_ID, request.context
ira = request.registry['ir.attachment']
iuv = request.registry['ir.ui.view']
But in this tables not present any one url. I can not understanding how it generate path for all pages. Where is it data stored?
I wrote own module but pages from it not present in sitemap.xml and keywords not correctly saved and displayed.
I tried extend my models such as:
class pr_info_pages(models.Model):
_name = 'pr_filials.pr_info_pages'
_inherit = ['mail.thread', 'website.seo.metadata', 'website.published.mixin']
but nothing changed...
How i can add my urls to sitemap and normally store keywords?
For keywords you need use in model:
_inherit = ['mail.thread', 'website.seo.metadata']
Also, when you generate page data you need put to page 'main_object'. This is the dictionary element that contains the object of your model. For example:
return http.request.render(_your_template_, {
'page_data': page_data,
'main_object': _object_
})
I want to facet the results based on the different model_names (classes) returned. Is there an easy way to do this?
Have you tried adding a SearchIndex field with this information? E.g.
class NoteIndex(SearchIndex, indexes.Indexable):
title = CharField(model_attr='title')
facet_model_name = CharField(faceted=True)
def get_model(self):
return Note
def prepare_facet_model_name(self, obj):
return "note"
class MemoIndex(SearchIndex, indexes.Indexable):
title = CharField(model_attr='title')
facet_model_name = CharField(faceted=True)
def get_model(self):
return Memo
def prepare_facet_model_name(self, obj):
return "memo"
And so on, simply returning a different string for each search index. You could also create a mixin and return the name of the model returned by get_model too.
Presuming you've added this field to each of your SearchIndex definitions, just chain the facet method to your results.
results = form.search().facet('facet_model_name')
Now the facet_counts method will return a dictionary with the faceted fields and count of results for each facet value, in this case, the model names.
Note that the field here is labeled verbosely to avoid a possible conflict with model_name, a field added by Haystack. It's not faceted, and I'm not sure if duplicating it will cause a conflict.
If you just want to filter on the model type, you can use the ModelSearchForm
The Docs have a really good walk-through for this.
The minimum you'll need:
is to add faceted=True to the params of your model_names field.
Rebuild your schema and indices.
add .facet('model_names') to whatever SearchQuerySet you're wanting to facet.
More explanation on the question would enable a more complete answer.