How to work with models in django(Important)-2


 
 3. select query how to write in django model/view:

I wanted to know is there anything equivalent to:
 
select columnname from tablename

Like Django tutorial says:
 
Entry.objects.filter(condition)

fetches all the objects with the given condition. It is like:
 
select * from Entry where condition

But I want to make a list of only one column
 
Entry.objects.values_list('column_name', flat=True).filter(condition)
 
 
 
4. let us consider the count() method  with example



#models.py

class Subjects(models.Model)
    ....
    name = models.ForeignKey(User, unique=False)
    ....
    number_of_followers = models.IntegerField( I want to have something like this: SELECT COUNT( DISTINCT name ) FROM school_subjects; ) 


 
 
solution:
=======

Subjects.objects.all().count()
 
or
 
 
school_subjects.objects.all().distinct('name').count() 
 
 
 
5. where we will write the query  example :
 
class Manager(object):

    # SNIP some housekeeping stuff..

    def get_query_set(self):
        return QuerySet(self.model, using=self._db)

    def all(self):
        return self.get_query_set()

    def count(self):
        return self.get_query_set().count()

    def filter(self, *args, **kwargs):
        return self.get_query_set().filter(*args, **kwargs)
 

No comments:

Post a Comment