0

I have following models (simplified) in Django app:

class Company(BaseModel):
    user = models.OneToOneField(User)
    title = models.CharField(max_length=128)

class Event(BaseModel):
    company= models.ForeignKey(Company)
    description = models.TextField(verbose_name="Description", blank=True,null=True,max_length=200,default="")

in one of my views, I want to count Event objects for company "owned" by logged user. to access company object I use something like request.user.company

How can I count all Event objects related to single company?

EDIT:

I think I asked wrong question. What I want to do: I select single event object:

event = Event.objects.get(uuid=event_uuid)

and now I want to get number of Event but within single company, not global ID.

1
  • 1
    write data sample and expected result. Commented Jun 1, 2013 at 13:32

1 Answer 1

2

I found hard to understand your question, do you want to count Event associated to a given Company?

c = Company.objects.get(...)
event_n = Event.objects.filter(company=c).count()

or

n = 2
event_n = Event.objects.filter(company__pk=n).count()

or

u = User.objects.get(...)
event_n = Event.objects.filter(company__user=u).count()

Do you want to collect one (some) company (companies) with the number of Event associated?

from django.db.models import Count
company = Company.objects.filter(pk=n).annotate(event_n=Count('event')).get()
print company.event_n

or

companies = Company.objects.filter(...).annotate(event_n=Count('event'))
for c in companies:
    print c.event_n

If you already have an event and you want the number of events associated to its company you can try

e = Event.objects.get(...)
event_n = Event.objects.filter(company=e.company).count()

or

n = 3
e = Event.objects.filter(pk=n).annotate(event_n=Count('company__event')).get()
print e.event_n
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for being unclear. So, I have several Company objects. Each of them has multiple events. When I show single event, I want to display number of this single event (not count) within parent company. Example: I have Event1 assigned to Company1 Event2 assigned to Company2 Event3 assigned to Company1 then, when displaying Event3 I want to show "ID:2"
An example id/primary key of your Event. Instead of pk=3 you can use uuid=event_uuid or whatever you like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.