tags:

views:

46

answers:

3

I have these two models:

class CommonVehicle(models.Model):
   year = models.ForeignKey(Year)
   series = models.ForeignKey(Series)
   engine = models.ForeignKey(Engine)
   body_style = models.ForeignKey(BodyStyle)
   ...

class Vehicle(models.Model):    
   objects = VehicleManager()
   stock_number = models.CharField(max_length=6, blank=False)
   vin = models.CharField(max_length=17, blank=False)
   common_vehicle = models.ForeignKey(CommonVehicle)
   ....

What I want to do is to have a count of how many times a given CommonVehicle object is used in the Vehicle class. So far my attempts are giving me one number, which is a total of all the records. How can I have the count being the total appearances for each CommonVehicle

Update 1 I was thinking something like this could work:

related_count = 0
for vehicle in vehicles:
    related_count += Vehicle.objects.filter(common_vehicle=vehicle).count()
+2  A: 
somecommonvehicle.vehicle_set.count()
Ignacio Vazquez-Abrams
Don't mean to be much of a bother, but this answer is a bit vague
Stephen
Take the "given `CommonVehicle` object" you have, access the `vehicle_set` attribute, and call the `count()` method on it.
Ignacio Vazquez-Abrams
A: 

I am currently developing a django app whose purpose is to solve this kind problem :

https://code.google.com/p/django-cube/

The documentation is not up-to-date, as I am constantly modifying the code (for now... It's only the beginning of the project). Here is the code you would use :

cube = Cube(['common_vehicle'], Vehicle.objects.all(), len)

The you can iterate on the cube for having all the counts for all the possible CommonVehicles :

for coords, value in cube.iteritems():
    #will print <CommonVehicule unicode representation> <count for this common vehicule>
    print coords.common_vehicule, measure

Or directly get the count for a CommonVehicule :

cube[Coords(common_vehicle=a_common_veh)]

A lot of other cool features are (will be) available ...

PS : the app allows to create multidimensional aggregates over a django queryset, OLAP-style ... Cube(['common_vehicle'], Vehicle.objects.all(), len) actually represents a cube whose dimensions are ['common_vehicle'], base queryset is Vehicle.objects.all() and aggregation function is len.

sebpiq
This looks interesting.....I'll give it a try too and see...hope you finish soon :)
Stephen
Yeah ! I'm actively pushing it, so it should be more stable, and more documented in the next few days ... And the syntax should be better.
sebpiq
A: 

Found that the question is closely related to: this

I should be doing this:

vehicles = CommonVehicle.objects.annotate(related_count=Count('vehicle')).all()

Then at the template where the count will be appearing:

{% for vehicle in vehicles %}
   ...
   {{ vehicle.related_count }}
   ...
{% endfor %}
Stephen