Django和PostgreSQL数据库

model表示在models。py里定义的一个类,比如scan,asset,ticket,里面有各种各样的数据

1.过滤用filter,得到符合要求的queryset

model.objects.filter(IP_Address=。。。。)

【Returns a new QuerySet containing objects that match the given lookup parameters.】

要用for item in来循环queryset,得到每一个小语句(小的object,object.属性)

2. 如果确定有且只有一个,就用get

model.objects.get(uuid=newscan.uuid)

3. 得到最新状态。属于该用户的所有scan,状态和openvas同步

Scan.objects.update_by_user(request.user)

4. 创建条目。

model.objects.create(属性=值)

5. user=request.user

  client = request.user.get_profile().client

  如得到该用户在asset里的值,用ass=Asset.objects.filter(client=client)

6. "__" 用于链接

  例如Ticket module里有asset的foreignkey指向Asset,Asset有module指向Module。所以从Ticket里读取module.id 要用【asset__module__id = module.id】

假设我有两个表(model),分别叫useraccount和userrole:

class UserAccount(meta.Model): 

    person = meta.ForeignKey(Person, core=True) 

    account = meta.ForeignKey(User, core=True)

class UserRole(meta.Model): 

    account = meta.ForeignKey(UserAccount, core=True) 

    group = meta.ForeignKey(Group, core=True) 

    active = meta.BooleanField(_('Active?'), default=True) 

如果我知道useraccount中某个字段(field)的值,那么我就能取到相应的userrole:

userroles.get_object(account__person__id__exact=xxx)

userroles.get_object(account__account__id__exact=xxx)

userroles.get_object(account__id__exact=xxx)

7. ForeignKey建立一个外连接。在表中显示变成_id

比如

models里publisher = models.ForeignKey(Publisher)
数据库里显示
"publisher_id" integer NOT NULL REFERENCES "books_publisher" ("id") DEFERRABLE INITIALLY DEFERRED,

ManyToManyField是多对多,会创建一个下属的新表,比如*.scan_asset,里面是scan_id和asset_id的对应关系。

比如

models里authors = models.ManyToManyField(Author)
数据库里显示
CREATE TABLE "books_book_authors" ( "id" serial NOT NULL PRIMARY KEY, "book_id" integer NOT NULL REFERENCES "books_book" ("id") DEFERRABLE INITIALLY DEFERRED, "author_id" integer NOT NULL REFERENCES "books_author" ("id") DEFERRABLE INITIALLY DEFERRED, UNIQUE ("book_id", "author_id") )

http://blog.csdn.net/shanliangliuxing/article/details/7599155

 

 

https://docs.djangoproject.com/en/dev/topics/db/queries/

你可能感兴趣的:(PostgreSQL)