12/10/2017

Django queryset simple tutorial


I have 4 objects in my table. The table name is 'Post'.



In models.py, the db class is like that:
class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title


So, let's train how to access the db and handle this.
Above all, you have to makemigrations, migrate after adding the db class code.

>python manage.py makemigrations
>python manage.py migrate


----
OK, train to the QuerySet (we call the dango query as QuerySet),
input this command in the console.
>python manage.py shell


OK, so now let's see the some commands
I will introduce very simple and useful commands.


1. show all objects

>from webapp.models import Post
: db import
>Post.objects.all()




2. access specific object

- first object
>Post.objects.all().first()
- last object
>Post.objects.all().last()
- 3rd object
>Post.objects.all()[2]




very easy right? ๐Ÿ˜ด


3. element value change in object and save

> obj = Post.objects.all()[2]
>obj.title = 'a_title_3'
>obj.save()






4. object add and save

>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()


5. Checking for empty queryset in Django

if table_name.objects.all().count() == 0:
     print('none')


6. auto increase primary field

id = models.AutoField(primary_key=True)


7. Query datetime by today, yesterday's date 

visitor table class is like that:
class visitor_ss2r(models.Model):
    id = models.AutoField(primary_key=True)
    count = models.PositiveIntegerField(default=0)
    day_visiting = models.DateField(auto_now=True)

today search
(notice!) import datetime 
visitor.objects.get(day_visiting=datetime.date.today())
or
visitor.objects.filter(day_visiting=datetime.date.today()).count()
yesterday search
today = datetime.date.today()
yesterday = today - datetime.timedelta(days = 1)
visitor.objects.get(day_visiting=today)
or
visitor.objects.filter(day_visiting=yesterday).count()

8. object delete

outdated_day = today - datetime.timedelta(days = 30)
obs = visitor_ss2r.objects.filter(day_visiting=outdated_day)
if len(obs) > 0:
    obs.delete()


9. admin page DB field view

Add def __str__(self): .....  show below code!

class visitor_ss2r(models.Model):
    id = models.AutoField(primary_key=True)
    count = models.PositiveIntegerField(default=0)
    day_visiting = models.DateField(auto_now=True)

    def __str__(self):
        return 'Date: ' + str(self.day_visiting)

then you can see like that in admin page


more detail
in admin.py, we can make column list like that:

class visitor_ss2r_Admin(admin.ModelAdmin):
    list_display = ('id', 'count', 'day_visiting')
admin.site.register(visitor_ss2r, visitor_ss2r_Admin)



R. reference

Fastest way to get the first object from a queryset in django?https://stackoverflow.com/questions/5123839/fastest-way-to-get-the-first-object-from-a-queryset-in-django

Making queries (Django officials page)
https://docs.djangoproject.com/en/2.0/topics/db/queries/




No comments:

Post a Comment