English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django 모델(Model)

모델은 데이터베이스 테이블이나 콜렉션을 표현하는 클래스이며, 이 클래스의 각 속성은 테이블이나 콜렉션의 필드입니다. 모델은 app/models.py에서 정의(우리의 예제에서는 myapp/models.py)

모델 생성

아래는 Dreamreal 모델 인스턴스를 생성하는 방법입니다. −

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
from django.db import models
 class Dreamreal(models.Model):
    website = models.CharField(max_length = 50)
    mail = models.CharField(max_length = 50)
    name = models.CharField(max_length = 50)
    phonenumber = models.IntegerField()
    class Meta:
       db_table = "dreamreal"

모델은 django.db.models.Model을 상속받습니다.

우리의 클래스는4개의 속성(3 CharField과1개의 정수), 이는 테이블의 필드가 됩니다.

Meta 클래스와 db_table 속성을 사용하여 실제 테이블이나 콜렉션 이름을 정의할 수 있습니다. Django는 테이블이나 콜렉션을 자동으로 이름을 지정합니다: myapp_modelName. 이 클래스는 테이블 이름을 강제로 지정합니다.

django.db.models에서 더 많은 필드의 타입에 대해 더 알고 싶다면 다음 URL을 참조하세요:

https://docs.djangoproject.com/en/1.5/ref/models/fields/#field-types

모델을 생성한 후 Django가 실제 데이터베이스를 생성해야 합니다. −

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
$python manage.py syncdb

데이터 작업(CRUD)

让我们创建一个“crudops”의 뷰를 만들어 보자. 모델에서 CRUD 작업을 어떻게 수행할 수 있는지 확인해 보겠습니다. 지금 myapp/views.py 그런 다음 −

myapp/views.py

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
from myapp.models import Dreamreal
 from django.http import HttpResponse
 def crudops(request):
    #엔트리 생성
    dreamreal = Dreamreal(
       website = "www.polo.com", mail = "[email protected]", 
       name = "sorex", phonenumber = "002376970"
    )
    dreamreal.save()
    #Read ALL entries
    objects = Dreamreal.objects.all()
    res = 'Printing all Dreamreal entries in the DB : <br>'
    for elt in objects:
       res += elt.name+"<br>"
    #Read a specific entry:
    sorex = Dreamreal.objects.get(name = "sorex")
    res += 'Printing One entry <br>'
    res += sorex.name
    #Delete an entry
    res += '<br> Deleting an entry <br>'
    sorex.delete()
    #Update
    dreamreal = Dreamreal(
       website = "www.polo.com", mail = "[email protected]", 
       name = "sorex", phonenumber = "002376970"
    )
    dreamreal.save()
    res += 'Updating entry<br>'
    dreamreal = Dreamreal.objects.get(name = 'sorex')
    dreamreal.name = 'thierry'
    dreamreal.save()
    return HttpResponse(res)

其他数据操作

让我们来探讨可以对模型做的其他操作。需要注意的是 CRUD 操作都做对模型的实例,现在我们将直接表示模型类的工作。

让我们创建一个“datamanipulation”视图在 myapp/views.py

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
from myapp.models import Dreamreal
 from django.http import HttpResponse
 def datamanipulation(request):
    res = ''
    #Filtering data:
    qs = Dreamreal.objects.filter(name = "paul")
    res += "Found : %s results<br>"%len(qs)
    #Ordering results
    qs = Dreamreal.objects.order_by("name")
    for elt in qs:
       res += elt.name + <br>'
    return HttpResponse(res)

모델 연결

Django ORM 제공3이 방식으로 모델을 연결하면 −

우리가 여기서 볼 첫 번째 예제는 일대다 관계입니다. 위의 예제에서 보면, 회사는 여러 개의 온라인 웹사이트를 가질 수 있습니다. 이러한 관계를 정의하는 것은 django.db.models.ForeignKey를 사용하여 완성됩니다 -

myapp/models.py

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
from django.db import models
 class Dreamreal(models.Model):
    website = models.CharField(max_length = 50)
    mail = models.CharField(max_length = 50)
    name = models.CharField(max_length = 50)
    phonenumber = models.IntegerField()
    online = models.ForeignKey('Online', default = 1)
    class Meta:
       db_table = "dreamreal"
 class Online(models.Model):
       domain = models.CharField(max_length = 30)
    class Meta:
       db_table = "online"

myapp을 업데이트할 수 있습니다/models.py에서 보면, 우리는 온라인 모델을 추가하고 Dreamreal 모델에 연결했습니다.

manage.py shell을 통해 모든 작업을 수행하는 방법을 알아보겠습니다 −

먼저 Django shell을 사용하여 몇 가지 회사(Dreamreal 항목)를 생성하는 방법을 테스트해 보겠습니다 −

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
$python manage.py shell
 >>> from myapp.models import Dreamreal, Online
 >>> dr1 = Dreamreal()
 >>> dr1.website = 'company1.com'
 >>> dr1.name = 'company1'
 >>> dr1.mail = 'contact@company1'
 >>> dr1.phonenumber = '12345'
 >>> dr1.save()
 >>> dr2 = Dreamreal()
 >>> dr1.website = 'company2.com'
 >>> dr2.website = 'company2.com'
 >>> dr2.name = 'company2'
 >>> dr2.mail = 'contact@company2'
 >>> dr2.phonenumber = '56789'
 >>> dr2.save()

현재 몇 가지 대리管网역이 있습니다 −

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
>>> on1 = Online()
 >>> on1.company = dr1
 >>> on1.domain = "site1.com"
 >>> on2 = Online()
 >>> on2.company = dr1
 >>> on2.domain = "site2.com"
 >>> on3 = Online()
 >>> on3.domain = "site3.com"
 >>> dr2 = Dreamreal.objects.all()[2]
 >>> on3.company = dr2
 >>> on1.save()
 >>> on2.save()
 >>> on3.save()

Online 도메인을 통해 호스팅 회사(Dreamreal 항목)의 속성에 접근하는 것은 매우 간단합니다 -

 # 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
>>> on1.company.name

Dreamreal에서 운영하는 모든 온라인 도메인을 알고 싶다면, 다음과 같은 코드를 사용합니다 -

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
>>> dr1.online_set.all()

QuerySet을 얻기 위해 모든 작업 메서드를 기억해야 합니다. 이전에 본 것처럼(filter, all, exclude, order_by...)

또한, 필터 작업을 위해 링크 모델 속성을 접근할 수 있습니다. 예를 들어, 모든 Online 도메인이 Dreamreal 이름에 'company'가 포함된 것을 얻고 싶다면,-

# 파일 이름: example.py
# 저작권: 2020 By w3codebox
# 작성자: ko.oldtoolbag.com
# 날짜: 2020-08-08
>>> Online.objects.filter(company__name__contains='company')

주의 - 이 퀘리는 SQL 데이터베이스만을 지원합니다. 비관계형 데이터베이스에서는 연결이 없으며 두 개의 "_"가 있습니다.

그러나 이는 OneToOneField를 사용하여 모델을 링크하는 유일한 방법이 아닙니다. 또한 OneToOneField가 있습니다. 이는 두 개체 간의 관계가 유일한 링크 관계임을 보장합니다. 만약 위의 예제에서 OneToOneField를 사용하면, 이는 각 Dreamreal 항목에 대해 하나의 Online 항목만이 해당한다는 의미입니다.

마지막으로, ManyToManyField 테이블 간(NN)의 관계는 모두 SQL 데이터베이스 기반입니다.