logo
down
shadow

Django query ForeignKey Count() zero


Django query ForeignKey Count() zero

By : Jowe
Date : November 20 2020, 03:01 PM
it should still fix some issue The direction of LEFT JOIN depends on the object, where you start the query. If it start on Menu you will never see a FoodType unused by selected Menu items. Then is important to filter (by Truck in your case) such way that also null value Menu.id is allowed in order to can get Count == 0.
code :
from django.db.models import Q
qs = (
    FoodType.objects
    .filter(Q(menu_set__id_truck=3) | Q(menu_set__id__isnull=True))
    .values()   # not necessary, but useful if you want a dict, not a Model object
    .annotate(cnt=models.Count("menu_set__id"))
)
>>> print(str(qs.query))
SELECT foodtype.id, foodtype..., COUNT(menu.id) AS cnt
FROM foodtype
LEFT OUTER JOIN menu ON (foodtype.id = menu.id_foodtype)
WHERE _menu.id_truck = 3 OR menu.id IS NULL)
GROUP BY foodtype.id
class Menu(models.Model):
    id_foodtype = models.ForeignKey('FoodType', on_delete=models.DO_NOTHING,
                                    db_column='id_foodtype', related_name='menu_set'))
    ...


Share : facebook icon twitter icon
Django newbie question: get count of associated ForeignKey, conditional on field within the ForeignKey table?

Django newbie question: get count of associated ForeignKey, conditional on field within the ForeignKey table?


By : user1900558
Date : March 29 2020, 07:55 AM
Any of those help Newbie question. I have Django models that look like this: , If I remember correctly,
code :
leaderboard = VideoUser.objects. \
        .annotate(num_submissions=Count('videosubmission')) \
        .filter(num_submissions__gt=0, video__problem_video=False).order_by('-num_submissions')
Django Query Performance: Unidirectional inclusion using ForeignKey vs. Bidirectional using ForeignKey & Related_nam

Django Query Performance: Unidirectional inclusion using ForeignKey vs. Bidirectional using ForeignKey & Related_nam


By : Johen Flores
Date : March 29 2020, 07:55 AM
Django get count on a ForeignKey

Django get count on a ForeignKey


By : Daniele Caschili
Date : March 29 2020, 07:55 AM
Does that help I need to get the total count of all contacts that belong to a group, but from within the model called batch....
code :
return self.group.contact_set.count()
Django - Follow a backward ForeignKey and then a ForeignKey (query)

Django - Follow a backward ForeignKey and then a ForeignKey (query)


By : faisal
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Because all() returns a queryset, which is a collection of items; theplace is an attribute on an individual Step, not on the collection.
The way to do this type of query is to start from the class you want to retrieve, and follow the relationships within the query using the double-underscore syntax. So:
code :
Picture.objects.filter(theplace__step__trip=selectedtrip)
Django 1.10 Count on Models ForeignKey

Django 1.10 Count on Models ForeignKey


By : Bayes ML
Date : March 29 2020, 07:55 AM
hop of those help? I guess this must be simple, but I've been trying for hours and can't find anything to help. , Views.py
code :
from django.shortcuts import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.db.models import Count

from .models import TemplateType
from .models import TemplateFile

def home(request):
    queryset = TemplateType.objects.order_by('type_title').annotate(num_file=Count('file_count'))

    context = {
        "object_list": queryset,
        "title": "Home",
    }
    return render(request, "index.html", context)
<div class="row">
        {% for obj in object_list %}
        <div class="template_type col-md-6">
            <a href="{{ obj.get_absolute_url }}">
                <h4>{{ obj.type_title }}</h4>
            </a>
            <p>{{ obj.type_short_description }}</p>
            <button class="btn btn-primary" type="button">Templates <span class="badge">{{ obj.num_file }}</span></button>
        </div>
        {% endfor %}
    </div>
Related Posts Related Posts :
  • Django Class Based View with get_queryset()
  • Django Rest Framework error: {"user":["This field is required."]
  • join two queries together as one - django
  • How to display the data contained in Django models in a Django Dropdown menu form?
  • Django: how to get the request object in urls.py
  • db_index in django as raw sql query
  • Removing unnecessary filters from URL django-filter
  • Is there a standard way to mock Django models?
  • My form fields are no longer coming though on the update page?
  • Filtering select field options in django-admin
  • Trying to use Docker with Django but server not starting
  • Does a foreign key object have a unique id value?
  • How to render/retrieve "field[]" in django forms?
  • TzInfo error when unsing Func() on a DatetimeField
  • DJango authentication User search not working properly
  • How to rename Table name in Django?
  • send just a specific filed on ModelSerializer to client - django rest framework
  • Deploying Django app on Ubuntu 16.04 apache2 with mod_wsgi
  • Django Rest Framework - Override serializer create method for model with self-referential M2M field
  • Running cookiecutter django on an intranet
  • Django wagtail getting page children with levels
  • How to delete an object after 24hrs since creation of the same
  • Django Using Slug Field for Detail URL
  • Vue and Django Development Environment
  • DRF Serializer handling generated field
  • How to use django-phonenumber_field in forms.py?
  • Django default at database
  • request.FILES empty, though file is present in request
  • Django: Not fetching the same object
  • Add Billing Address Validation in Stripe.js
  • get any instance (if exist) or create new for any child of abstract model
  • How to configure Django with Webpack/React using create-react-app on Ubuntu server
  • post_save doesn't list tags
  • Doubts regarding Django views
  • Django many-to-many add having inconsistent effect in functions, works on console
  • django restful api - how to serialize foreign keys
  • Target WSGI script cannot be loaded as a python module and ImportError: No module named 'django'
  • How to put session data in SetUp() - Django testing
  • How to redirect from html page to view and post data in Django
  • Access pk from related model using prefetch and to_attr
  • Image does not upload using createview from template django
  • How to exclude values in django aggregation?
  • UpdateView problem : cleaned data passed in url not in instance
  • Using template tag in ModelAdmin.readonly_fields method
  • Fix AttributeError: 'str' object has no attribute 'HTTP_201_CREATED'
  • modelformset_factory doesnt save instances to database
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org