Count number of instances of a City object in a model syntaxCount the number occurrences of a character in a stringdjango - inlineformset_factory with more than one ForeignKeyAttributeError - type object 'Services' has no attribute 'service_price'Radio buttons in django adminDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fieldDjango Model Issue In Multilevel Inheritance.Is there a simple way to create Chained Dynamic Drop Down List in Django Admin Site?How to check if Django Signal works?

Should I give professor gift at the beginning of my PhD?

How to handle self harm scars on the arm in work environment?

Does Disney no longer produce hand-drawn cartoon films?

How to tell your grandparent to not come to fetch you with their car?

Generate a Graeco-Latin square

Trapping Rain Water

How does an ordinary object become radioactive?

Why is one of Madera Municipal's runways labelled with only "R" on both sides?

What is the fastest method to figure out which keys contain certain notes?

How to signal to my players that the following part is supposed to be played on fast forward?

Logarithm of exponential

Overlapping String-Blocks

Were Alexander the Great and Hephaestion lovers?

How to hide an urban landmark?

Pre-1972 sci-fi short story or novel: alien(?) tunnel where people try new moves and get destroyed if they're not the correct ones

Fixing obscure 8080 emulator bug?

Is it possible to 'live off the sea'

Project Euler #7 10001st prime in C++

Share calendar details request from manager's manager

What is the actual quality of machine translations?

Impedance ratio vs. SWR

What's up with this leaf?

PhD - Well known professor or well known school?

Taxi Services at Didcot



Count number of instances of a City object in a model syntax


Count the number occurrences of a character in a stringdjango - inlineformset_factory with more than one ForeignKeyAttributeError - type object 'Services' has no attribute 'service_price'Radio buttons in django adminDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fieldDjango Model Issue In Multilevel Inheritance.Is there a simple way to create Chained Dynamic Drop Down List in Django Admin Site?How to check if Django Signal works?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I will briefly explain what I am trying to do.



A user will sign up with email, first and last name, and then select a city (handled by the model called Waitlist).



I am using django_cities_light for city selection.



I want to define a queryset that counts the number of times a specific city has been selected and then output that number onto my template_name page.



Ex) 3 users sign up, 2 people select London as their city, thus there are 2 instances of the London city object in my Waitlist model. I want to be able to do this easily for multiple cities.



I want to then render this 2 out using for London in waitlist.qs for example (I'm not sure of the syntax hence why I'm asking).



I will show what I have done so far and if someone could explain to me how to define the queryset properly, I would appreciate it!



views.py



class HomeView(TemplateView):
template_name = 'home/home.html'
def get(self, request, *args, **kwargs):
london = Waitlist.objects.get(??)
context =
'london': london,

return render(request, self.template_name, context)


models.py



class Waitlist(models.Model):
first_name = models.CharField(max_length=30, null=True)
last_name = models.CharField(max_length=30, null=True)
email = models.CharField(max_length=40, null=True)
city = models.ForeignKey(City, null=True, blank=True, on_delete=models.CASCADE)









share|improve this question






























    2















    I will briefly explain what I am trying to do.



    A user will sign up with email, first and last name, and then select a city (handled by the model called Waitlist).



    I am using django_cities_light for city selection.



    I want to define a queryset that counts the number of times a specific city has been selected and then output that number onto my template_name page.



    Ex) 3 users sign up, 2 people select London as their city, thus there are 2 instances of the London city object in my Waitlist model. I want to be able to do this easily for multiple cities.



    I want to then render this 2 out using for London in waitlist.qs for example (I'm not sure of the syntax hence why I'm asking).



    I will show what I have done so far and if someone could explain to me how to define the queryset properly, I would appreciate it!



    views.py



    class HomeView(TemplateView):
    template_name = 'home/home.html'
    def get(self, request, *args, **kwargs):
    london = Waitlist.objects.get(??)
    context =
    'london': london,

    return render(request, self.template_name, context)


    models.py



    class Waitlist(models.Model):
    first_name = models.CharField(max_length=30, null=True)
    last_name = models.CharField(max_length=30, null=True)
    email = models.CharField(max_length=40, null=True)
    city = models.ForeignKey(City, null=True, blank=True, on_delete=models.CASCADE)









    share|improve this question


























      2












      2








      2








      I will briefly explain what I am trying to do.



      A user will sign up with email, first and last name, and then select a city (handled by the model called Waitlist).



      I am using django_cities_light for city selection.



      I want to define a queryset that counts the number of times a specific city has been selected and then output that number onto my template_name page.



      Ex) 3 users sign up, 2 people select London as their city, thus there are 2 instances of the London city object in my Waitlist model. I want to be able to do this easily for multiple cities.



      I want to then render this 2 out using for London in waitlist.qs for example (I'm not sure of the syntax hence why I'm asking).



      I will show what I have done so far and if someone could explain to me how to define the queryset properly, I would appreciate it!



      views.py



      class HomeView(TemplateView):
      template_name = 'home/home.html'
      def get(self, request, *args, **kwargs):
      london = Waitlist.objects.get(??)
      context =
      'london': london,

      return render(request, self.template_name, context)


      models.py



      class Waitlist(models.Model):
      first_name = models.CharField(max_length=30, null=True)
      last_name = models.CharField(max_length=30, null=True)
      email = models.CharField(max_length=40, null=True)
      city = models.ForeignKey(City, null=True, blank=True, on_delete=models.CASCADE)









      share|improve this question
















      I will briefly explain what I am trying to do.



      A user will sign up with email, first and last name, and then select a city (handled by the model called Waitlist).



      I am using django_cities_light for city selection.



      I want to define a queryset that counts the number of times a specific city has been selected and then output that number onto my template_name page.



      Ex) 3 users sign up, 2 people select London as their city, thus there are 2 instances of the London city object in my Waitlist model. I want to be able to do this easily for multiple cities.



      I want to then render this 2 out using for London in waitlist.qs for example (I'm not sure of the syntax hence why I'm asking).



      I will show what I have done so far and if someone could explain to me how to define the queryset properly, I would appreciate it!



      views.py



      class HomeView(TemplateView):
      template_name = 'home/home.html'
      def get(self, request, *args, **kwargs):
      london = Waitlist.objects.get(??)
      context =
      'london': london,

      return render(request, self.template_name, context)


      models.py



      class Waitlist(models.Model):
      first_name = models.CharField(max_length=30, null=True)
      last_name = models.CharField(max_length=30, null=True)
      email = models.CharField(max_length=40, null=True)
      city = models.ForeignKey(City, null=True, blank=True, on_delete=models.CASCADE)






      python django






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 17:10









      petezurich

      4,02082036




      4,02082036










      asked Mar 24 at 17:04









      TrillaTrilla

      3279




      3279






















          1 Answer
          1






          active

          oldest

          votes


















          1














          may be you need something like this, get all cities, and prepare data:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          query = Waitlist.objects.all()
          data =
          for cname in query.values('city__name').distinct():
          city = cname['city__name']
          data[city] = query.filter(city__name=city)
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template



          % for city, details in data.items %
          <strong> city , total - length :<strong>
          <ul>
          % for wait_item in details %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>
          <hr>
          % endfor %


          if you need only the London
          in the view it should be:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          data = Waitlist.objects.filter(city__name__iexact='london')
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template:



           <strong>London, total - length :<strong>
          <ul>
          % for wait_item in data %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>


          details for the query you can read iexact, distinct






          share|improve this answer

























          • So for example, would I substitute London into cname? What would go into the data ? Also I keep getting an error that the return render is indented incorrectly no matter how I format it.

            – Trilla
            Mar 24 at 17:52











          • Okay, I see what you are doing. But what is the proper syntax for % for city, details in the data.items % would it be % for london in data.items % ?

            – Trilla
            Mar 24 at 19:15











          • There is also an error being thrown name 'query_order' is not defined, would it be better with just context?

            – Trilla
            Mar 24 at 19:16











          • now i hope i created the finished answer, where the count for the city in the total for each city in the template.

            – Bear Brown
            Mar 24 at 19:53











          • Thank you, it works perfectly. Where can I learn more about how to do this and the syntax? One last question, if I only want to display London in the template and not a forloop of every city with an instance (there may be hundreds of different cities), what would the syntax be?

            – Trilla
            Mar 24 at 20:05












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55326302%2fcount-number-of-instances-of-a-city-object-in-a-model-syntax%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          may be you need something like this, get all cities, and prepare data:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          query = Waitlist.objects.all()
          data =
          for cname in query.values('city__name').distinct():
          city = cname['city__name']
          data[city] = query.filter(city__name=city)
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template



          % for city, details in data.items %
          <strong> city , total - length :<strong>
          <ul>
          % for wait_item in details %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>
          <hr>
          % endfor %


          if you need only the London
          in the view it should be:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          data = Waitlist.objects.filter(city__name__iexact='london')
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template:



           <strong>London, total - length :<strong>
          <ul>
          % for wait_item in data %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>


          details for the query you can read iexact, distinct






          share|improve this answer

























          • So for example, would I substitute London into cname? What would go into the data ? Also I keep getting an error that the return render is indented incorrectly no matter how I format it.

            – Trilla
            Mar 24 at 17:52











          • Okay, I see what you are doing. But what is the proper syntax for % for city, details in the data.items % would it be % for london in data.items % ?

            – Trilla
            Mar 24 at 19:15











          • There is also an error being thrown name 'query_order' is not defined, would it be better with just context?

            – Trilla
            Mar 24 at 19:16











          • now i hope i created the finished answer, where the count for the city in the total for each city in the template.

            – Bear Brown
            Mar 24 at 19:53











          • Thank you, it works perfectly. Where can I learn more about how to do this and the syntax? One last question, if I only want to display London in the template and not a forloop of every city with an instance (there may be hundreds of different cities), what would the syntax be?

            – Trilla
            Mar 24 at 20:05
















          1














          may be you need something like this, get all cities, and prepare data:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          query = Waitlist.objects.all()
          data =
          for cname in query.values('city__name').distinct():
          city = cname['city__name']
          data[city] = query.filter(city__name=city)
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template



          % for city, details in data.items %
          <strong> city , total - length :<strong>
          <ul>
          % for wait_item in details %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>
          <hr>
          % endfor %


          if you need only the London
          in the view it should be:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          data = Waitlist.objects.filter(city__name__iexact='london')
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template:



           <strong>London, total - length :<strong>
          <ul>
          % for wait_item in data %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>


          details for the query you can read iexact, distinct






          share|improve this answer

























          • So for example, would I substitute London into cname? What would go into the data ? Also I keep getting an error that the return render is indented incorrectly no matter how I format it.

            – Trilla
            Mar 24 at 17:52











          • Okay, I see what you are doing. But what is the proper syntax for % for city, details in the data.items % would it be % for london in data.items % ?

            – Trilla
            Mar 24 at 19:15











          • There is also an error being thrown name 'query_order' is not defined, would it be better with just context?

            – Trilla
            Mar 24 at 19:16











          • now i hope i created the finished answer, where the count for the city in the total for each city in the template.

            – Bear Brown
            Mar 24 at 19:53











          • Thank you, it works perfectly. Where can I learn more about how to do this and the syntax? One last question, if I only want to display London in the template and not a forloop of every city with an instance (there may be hundreds of different cities), what would the syntax be?

            – Trilla
            Mar 24 at 20:05














          1












          1








          1







          may be you need something like this, get all cities, and prepare data:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          query = Waitlist.objects.all()
          data =
          for cname in query.values('city__name').distinct():
          city = cname['city__name']
          data[city] = query.filter(city__name=city)
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template



          % for city, details in data.items %
          <strong> city , total - length :<strong>
          <ul>
          % for wait_item in details %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>
          <hr>
          % endfor %


          if you need only the London
          in the view it should be:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          data = Waitlist.objects.filter(city__name__iexact='london')
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template:



           <strong>London, total - length :<strong>
          <ul>
          % for wait_item in data %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>


          details for the query you can read iexact, distinct






          share|improve this answer















          may be you need something like this, get all cities, and prepare data:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          query = Waitlist.objects.all()
          data =
          for cname in query.values('city__name').distinct():
          city = cname['city__name']
          data[city] = query.filter(city__name=city)
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template



          % for city, details in data.items %
          <strong> city , total - length :<strong>
          <ul>
          % for wait_item in details %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>
          <hr>
          % endfor %


          if you need only the London
          in the view it should be:



          class HomeView(TemplateView):
          template_name = 'home/home.html'

          def get(self, request, *args, **kwargs):
          data = Waitlist.objects.filter(city__name__iexact='london')
          context =
          'data': data,

          return render(request, self.template_name, context)


          and in the template:



           <strong>London, total - length :<strong>
          <ul>
          % for wait_item in data %
          <li> wait_item.first_name - wait_item.email </li>
          % endfor %
          </ul>


          details for the query you can read iexact, distinct







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 24 at 20:54

























          answered Mar 24 at 17:35









          Bear BrownBear Brown

          12.8k82548




          12.8k82548












          • So for example, would I substitute London into cname? What would go into the data ? Also I keep getting an error that the return render is indented incorrectly no matter how I format it.

            – Trilla
            Mar 24 at 17:52











          • Okay, I see what you are doing. But what is the proper syntax for % for city, details in the data.items % would it be % for london in data.items % ?

            – Trilla
            Mar 24 at 19:15











          • There is also an error being thrown name 'query_order' is not defined, would it be better with just context?

            – Trilla
            Mar 24 at 19:16











          • now i hope i created the finished answer, where the count for the city in the total for each city in the template.

            – Bear Brown
            Mar 24 at 19:53











          • Thank you, it works perfectly. Where can I learn more about how to do this and the syntax? One last question, if I only want to display London in the template and not a forloop of every city with an instance (there may be hundreds of different cities), what would the syntax be?

            – Trilla
            Mar 24 at 20:05


















          • So for example, would I substitute London into cname? What would go into the data ? Also I keep getting an error that the return render is indented incorrectly no matter how I format it.

            – Trilla
            Mar 24 at 17:52











          • Okay, I see what you are doing. But what is the proper syntax for % for city, details in the data.items % would it be % for london in data.items % ?

            – Trilla
            Mar 24 at 19:15











          • There is also an error being thrown name 'query_order' is not defined, would it be better with just context?

            – Trilla
            Mar 24 at 19:16











          • now i hope i created the finished answer, where the count for the city in the total for each city in the template.

            – Bear Brown
            Mar 24 at 19:53











          • Thank you, it works perfectly. Where can I learn more about how to do this and the syntax? One last question, if I only want to display London in the template and not a forloop of every city with an instance (there may be hundreds of different cities), what would the syntax be?

            – Trilla
            Mar 24 at 20:05

















          So for example, would I substitute London into cname? What would go into the data ? Also I keep getting an error that the return render is indented incorrectly no matter how I format it.

          – Trilla
          Mar 24 at 17:52





          So for example, would I substitute London into cname? What would go into the data ? Also I keep getting an error that the return render is indented incorrectly no matter how I format it.

          – Trilla
          Mar 24 at 17:52













          Okay, I see what you are doing. But what is the proper syntax for % for city, details in the data.items % would it be % for london in data.items % ?

          – Trilla
          Mar 24 at 19:15





          Okay, I see what you are doing. But what is the proper syntax for % for city, details in the data.items % would it be % for london in data.items % ?

          – Trilla
          Mar 24 at 19:15













          There is also an error being thrown name 'query_order' is not defined, would it be better with just context?

          – Trilla
          Mar 24 at 19:16





          There is also an error being thrown name 'query_order' is not defined, would it be better with just context?

          – Trilla
          Mar 24 at 19:16













          now i hope i created the finished answer, where the count for the city in the total for each city in the template.

          – Bear Brown
          Mar 24 at 19:53





          now i hope i created the finished answer, where the count for the city in the total for each city in the template.

          – Bear Brown
          Mar 24 at 19:53













          Thank you, it works perfectly. Where can I learn more about how to do this and the syntax? One last question, if I only want to display London in the template and not a forloop of every city with an instance (there may be hundreds of different cities), what would the syntax be?

          – Trilla
          Mar 24 at 20:05






          Thank you, it works perfectly. Where can I learn more about how to do this and the syntax? One last question, if I only want to display London in the template and not a forloop of every city with an instance (there may be hundreds of different cities), what would the syntax be?

          – Trilla
          Mar 24 at 20:05




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55326302%2fcount-number-of-instances-of-a-city-object-in-a-model-syntax%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해