Django add into many-to-many field for each item in a queryset?
Tag : python , By : Amin Amini
Date : March 29 2020, 07:55 AM
this one helps. Suppose I have the following model: , You could do a bulk_create on the through table. For example: blog = Blog.objects.get(…)
users = User.object.all()
User.blogs.through.objects.bulk_create(
[User.blogs.through(user_id=user.pk, blog_id=blog.pk) for user in users]
)
|
How do you loop through a Django queryset in an html file?
Date : March 29 2020, 07:55 AM
around this issue Why not just get the first 3 items only in your view and only return those into the context? That seems like it would be the simplest solution. first_3_reviews = Review.objects.filter(movie= movie)[:3]
{% for obj in review %}
{% if forloop.counter < 3 %}
<p> {% obj.review_text %} </p>
{% endif %}
{% endfor %}
|
How to get penultimate item from QuerySet in Django?
Tag : python , By : Caleb Ames
Date : March 29 2020, 07:55 AM
To fix the issue you can do How to get the penultimate item from Django QuerySet? I tried my_queryset[-2] (after checking whether the my_queryset length is greater than 1) as follows: , This code which produces an error scans = self.scans.all().order_by('datetime')
if len(scans)>1:
scan = scans[-2]
scans = self.scans.all().order_by('-datetime')
if len(scans)>1:
scan = scans[1]
|
Django queryset for list item
Date : March 29 2020, 07:55 AM
this will help You should create a new view, which get a pk of choosen movie and retrives all informations about it. # Add to urls.py
urlpatterns += [url(r'^detail/(?P<pk>\d+)/$', views.movie_detail, name='movie_detail')]
# Add to views.py
from django.shortcuts import get_object_or_404
def movie_detail(request, pk):
movie = get_object_or_404(movieTitle, pk=pk)
return render(request, 'movie_detail.html', {'movie': movie})
# movie_detail.html
<h1>Title: {{ movie.title }}</h1>
<img src="{{ movie.image }}">
{{ movie.description|linebreaks }}
<p>Year: {{ movie.year }}</p>
<p>Director: {{ movie.director }}</p>
# Your initial html
<body>
{% for movie in movies %}
<a href="{% url 'movie_detail' movie.pk %}">{{ movie.title }}</a>
{% endfor %}
</body>
|
Django get a queryset and filter by own queryset item
Tag : django , By : Richard Laksana
Date : March 29 2020, 07:55 AM
hop of those help? first of all, I cant find the way to explain what I'm intend to do properly so I'll try to do it the best way I can, hope it make sense to you. , try this GETS ALL ALCTIVE ITEMS articulos = Item.objects.all().filter(activo=True,)
l = []
for i in articulos:
# TRIES TO GET FILTERD VALUE FOR EACH ITEM
articulo = Item.objects.filter(pk=i.pk,cantidad_existente__lte=i.cantidad_minima)
if articulo:
l.append(articulo[0])
return render(request, template_name, {'items': l})
|