Working with Django Model

  1. Sub-queries used for query pk dee in  main talbe

Create your models here.
class projects(models.Model):
    #env = models.ForeignKey(deploy_env, on_delete=models.CASCADE)
    project_name = models.CharField(max_length=200)
    create_date = models.DateTimeField(default=0)
    owner = models.CharField(max_length=200)

    def __str__(self):
        return self.project_name
class AppEnv(models.Model):

    name = models.CharField(max_length=200, unique=True)
    def __str__(self):
        return self.name

class MGDeployEnv(models.Model):
    deploy_env = models.OneToOneField(minion_groups, on_delete=models.CASCADE)
    project_name = models.ForeignKey(projects, on_delete=models.CASCADE)
    env_name = models.ForeignKey(AppEnv, on_delete=models.CASCADE)
    pillar = models.TextField()
    state = models.TextField()
    current_version = models.CharField(max_length=200, blank=True)
    status = models.CharField(max_length=200, blank=True)
    comments = models.CharField(max_length=200, blank=True)
    update_on = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return str(self.deploy_env)
class tasks(models.Model): #question = models.ForeignKey(Question, on_delete=models.CASCADE) #project_name = models.ForeignKey(projects, on_delete=models.CASCADE) env = models.ForeignKey(deploy_env, on_delete=models.CASCADE) deploy_url = models.CharField(max_length=200) owner = models.CharField(max_length=200) date = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=200, blank=True) result = models.TextField(blank=True) def __str__(self): return self.deploy_url

1.1 Command line tests:

>> env_id=deploy_env.objects.filter(project_name_id=5)
>>> qt=tasks.objects.filter(env_id__in=env_id)
>>> qt.values()

<QuerySet [{‘deploy_url’: ‘testurl’, ‘id’: 11, ‘env_id’: 12, ….. etc

class tasks(models.Model):
    #question = models.ForeignKey(Question, on_delete=models.CASCADE)
    #project_name = models.ForeignKey(projects, on_delete=models.CASCADE)
    #env = models.ForeignKey(deploy_env, on_delete=models.CASCADE)
    env = models.ForeignKey(MGDeployEnv, on_delete=models.CASCADE)
    deploy_url = models.CharField(max_length=200)
    owner = models.CharField(max_length=200)
    date = models.DateTimeField(default=timezone.now)
    status = models.CharField(max_length=200, blank=True)
    result = models.TextField(blank=True)

    def __str__(self):
        return self.deploy_url

More Model Query:

There two methods to get the searching result, for example.

1.2 Foward query (query by main set)

if we would like get the all deploy environment of PROD,  or deploy environment of Projects test, we can do following query:

by project

pj=projects.objects.get(project_name=‘abc’)

pj.mgdeployenv_set.all()

or shorter 

projects.objects.get(project_name=‘cpg’).mgdeployenv_set.all()

<QuerySet [<MGDeployEnv: cpg_cons_be>, <MGDeployEnv: cpg_cons_all>]>

by environments

env = AppEnv.objects.get(name=’cons’)

env.mgdeployenv_set.all()

QuerySet [<MGDeployEnv: abc_cons_be>, <MGDeployEnv: abc_cons_all>]>

1.3 BackForward query(query by sub set)

by project

MGDeployEnv.objects.filter(project_name__in=projects.objects.filter(project_name=‘abc’))

<QuerySet [<MGDeployEnv: abc_cons_be>, <MGDeployEnv: abc_cons_all>]>

by environments

MGDeployEnv.objects.filter(env_name__in=AppEnv.objects.filter(name=‘cons’))

<QuerySet [<MGDeployEnv: abc_cons_be>, <MGDeployEnv: abc_cons_all>]>

 

as you can see, this 4 queries are the same.

 

Reference Links:

http://scottlobdell.me/2015/01/sql-database-best-practices-django-orm/ 

 

2. Many to Many

https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/

Standalone script with Django

I am going to run external script by invoking Django module, db models etc.

Here the refernece link from django official docs.:

https://docs.djangoproject.com/en/2.0/topics/settings/

However, for the quote of website which is not working for me:

import django
from django.conf import settings
from myapp import myapp_defaults

settings.configure(default_settings=myapp_defaults, DEBUG=True)
django.setup()

# Now this script or any imported module can use any part of Django it needs.
from myapp import models

simply I am using following code instead:

#!/usr/bin/env python3

import os
import sys

project_path="/home/liboma/saltmgt/"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saltmgt.saltmgt.settings")
sys.path.append(project_path)
#os.chdir(project_path)
if __name__ == '__main__':
    import django
    django.setup()
    from autocd.models import *
    <<your scripts>>

which is working fine for me.

Enjoy 🙂

other refernece links which helps:

  •  http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/
  • https://www.stavros.io/posts/standalone-django-scripts-definitive-guide/

 

Python-Django clean_data 和 cleaned_data

clean_data 和 cleaned_data

在我们使用Django的表单对象时我们会对表单对象进行验证,比如:
>>>python manage.py shell
>>>from pageage1 import MyForm
>>>form=MyForm({‘username’:’Eric’,’email’:’test@test.com’})
>>>form.is_valid()
True

如果验证通过,你可以通过form.clean_data访问这些验证通过的数据,不过这是在Django0.96中的方式,在Django1.0中这个属性变成了form.cleaned_data:

>>>form.clean_data # Django 0.96
>>>form.cleaned_data # Django 1.0