mirror of
https://github.com/netbox-community/netbox.git
synced 2024-05-10 07:54:54 +00:00
Implement get_subquery() for annotation of child object counts; Rename dcim.Site 'count_*' fields
This commit is contained in:
@ -4,6 +4,7 @@ import datetime
|
||||
import json
|
||||
|
||||
from django.core.serializers import serialize
|
||||
from django.db.models import Count, OuterRef, Subquery
|
||||
|
||||
from dcim.constants import LENGTH_UNIT_CENTIMETER, LENGTH_UNIT_FOOT, LENGTH_UNIT_INCH, LENGTH_UNIT_METER
|
||||
|
||||
@ -71,6 +72,23 @@ def model_names_to_filter_dict(names):
|
||||
}
|
||||
|
||||
|
||||
def get_subquery(model, field):
|
||||
"""
|
||||
Return a Subquery suitable for annotating a child object count.
|
||||
"""
|
||||
subquery = Subquery(
|
||||
model.objects.filter(
|
||||
**{field: OuterRef('pk')}
|
||||
).order_by().values(
|
||||
field
|
||||
).annotate(
|
||||
c=Count('*')
|
||||
).values('c')
|
||||
)
|
||||
|
||||
return subquery
|
||||
|
||||
|
||||
def serialize_object(obj, extra=None):
|
||||
"""
|
||||
Return a generic JSON representation of an object using Django's built-in serializer. (This is used for things like
|
||||
|
Reference in New Issue
Block a user