Django common operation for MySQL (using ORM)

Source: Internet
Author: User

For Django, the operational database basically uses the ORM it provides, native SQL also supports, where we discuss ORM

Let's create a database first

Create test Database

class Test (models. Model):    "" "    Test    INFO LIST" "= models. Charfield (U"nams", max_length=100, default=")

Action Add

 from Import Test # Increase " Sky "  = Test () test.name= nametest.save ()

Operation change Data No, add, if any, changes

From models import testimport Tracebackname = "Sky" try:     test = Test (name=name) except Exception:     test = Test () te St.name = Nametest.save ()

And there's an added way

From models import Testmodels.User.objects.create (name= ' sky ') dic = {' name ': ' Sky ',}test.objects.create (**dic)

For the query, the more commonly used is three kinds, is the type of Queryset

From models Import TESTV1 = Test.objects.all () # QuerySet, inner elements are object            # QuerySet, inner elements are dictionary v2 = Test.objects.all (). Values (' id ', ' caption ') # QuerySet, inner elements are tuples v3 = Test.objects.all (). Values_list (' id ', ' caption ')

# because the object cannot be observed in detail, I often use the method to operate
V4 = Test.objexts.filter (name= "Sky"). VALUES ()
And then operate on the V4.

For native SQL

Test.objects.raw ("select * from Test limit 2")

  

Django common operation for MySQL (using ORM)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.