---
title: "모델"
version: 2.2
locale: ko
source: https://docs.djangoproject.com/ko/2.2/topics/db/models/
canonical: https://djangodocs.dev/ko/2.2/topics/db/models/
---
# 모델

A model is the single, definitive source of information about your data. It
contains the essential fields and behaviors of the data you’re storing.
Generally, each model maps to a single database table.

The basics:

- Each model is a Python class that subclasses
  [`django.db.models.Model`](/ko/2.2/ref/models/instances/#django.db.models.Model).
- Each attribute of the model represents a database field.
- With all of this, Django gives you an automatically-generated
  database-access API; see [쿼리 만들기](/ko/2.2/topics/db/queries/).

## Quick example

This example model defines a `Person`, which has a `first_name` and
`last_name`:

```
from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
```

`first_name` and `last_name` are [fields](#fields) of the model. Each field is
specified as a class attribute, and each attribute maps to a database column.

The above `Person` model would create a database table like this:

```sql
CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);
```

Some technical notes:

- The name of the table, `myapp_person`, is automatically derived from
  some model metadata but can be overridden. See [Table names](/ko/2.2/ref/models/options/#table-names) for more
  details.
- An `id` field is added automatically, but this behavior can be
  overridden. See [Automatic primary key fields](#automatic-primary-key-fields).
- The `CREATE TABLE` SQL in this example is formatted using PostgreSQL
  syntax, but it’s worth noting Django uses SQL tailored to the database
  backend specified in your [settings file](/ko/2.2/topics/settings/).

## Using models

Once you have defined your models, you need to tell Django you’re going to *use*
those models. Do this by editing your settings file and changing the
[`INSTALLED_APPS`](/ko/2.2/ref/settings/#std-setting-INSTALLED_APPS) setting to add the name of the module that contains
your `models.py`.

For example, if the models for your application live in the module
`myapp.models` (the package structure that is created for an
application by the [`manage.py startapp`](/ko/2.2/ref/django-admin/#django-admin-startapp) script),
[`INSTALLED_APPS`](/ko/2.2/ref/settings/#std-setting-INSTALLED_APPS) should read, in part:

```
INSTALLED_APPS = [
    #...
    'myapp',
    #...
]
```

When you add new apps to [`INSTALLED_APPS`](/ko/2.2/ref/settings/#std-setting-INSTALLED_APPS), be sure to run
[`manage.py migrate`](/ko/2.2/ref/django-admin/#django-admin-migrate), optionally making migrations
for them first with [`manage.py makemigrations`](/ko/2.2/ref/django-admin/#django-admin-makemigrations).

## 필드

The most important part of a model – and the only required part of a model –
is the list of database fields it defines. Fields are specified by class
attributes. Be careful not to choose field names that conflict with the
[models API](/ko/2.2/ref/models/instances/) like `clean`, `save`, or
`delete`.

예제:

```
from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()
```

### Field types

Each field in your model should be an instance of the appropriate
[`Field`](/ko/2.2/ref/models/fields/#django.db.models.Field) class. Django uses the field class types to
determine a few things:

- The column type, which tells the database what kind of data to store (e.g.
  `INTEGER`, `VARCHAR`, `TEXT`).
- The default HTML [widget](/ko/2.2/ref/forms/widgets/) to use when rendering a form
  field (e.g. `<input type="text">`, `<select>`).
- The minimal validation requirements, used in Django’s admin and in
  automatically-generated forms.

Django ships with dozens of built-in field types; you can find the complete list
in the [model field reference](/ko/2.2/ref/models/fields/#model-field-types). You can easily write
your own fields if Django’s built-in ones don’t do the trick; see
[Writing custom model fields](/ko/2.2/howto/custom-model-fields/).

### Field options

Each field takes a certain set of field-specific arguments (documented in the
[model field reference](/ko/2.2/ref/models/fields/#model-field-types)). For example,
[`CharField`](/ko/2.2/ref/models/fields/#django.db.models.CharField) (and its subclasses) require a
[`max_length`](/ko/2.2/ref/models/fields/#django.db.models.CharField.max_length) argument which specifies the size
of the `VARCHAR` database field used to store the data.

There’s also a set of common arguments available to all field types. All are
optional. They’re fully explained in the [reference](/ko/2.2/ref/models/fields/#common-model-field-options), but here’s a quick summary of the most often-used
ones:

**[`null`](/ko/2.2/ref/models/fields/#django.db.models.Field.null)**

  If `True`, Django will store empty values as `NULL` in the database.
  Default is `False`.

**[`blank`](/ko/2.2/ref/models/fields/#django.db.models.Field.blank)**

  If `True`, the field is allowed to be blank. Default is `False`.

  Note that this is different than [`null`](/ko/2.2/ref/models/fields/#django.db.models.Field.null).
  [`null`](/ko/2.2/ref/models/fields/#django.db.models.Field.null) is purely database-related, whereas
  [`blank`](/ko/2.2/ref/models/fields/#django.db.models.Field.blank) is validation-related. If a field has
  [`blank=True`](/ko/2.2/ref/models/fields/#django.db.models.Field.blank), form validation will
  allow entry of an empty value. If a field has [`blank=False`](/ko/2.2/ref/models/fields/#django.db.models.Field.blank), the field will be required.

**[`choices`](/ko/2.2/ref/models/fields/#django.db.models.Field.choices)**

  A [sequence](https://docs.python.org/3/glossary.html#term-sequence) of 2-tuples to use as choices for this field. If this
  is given, the default form widget will be a select box instead of the
  standard text field and will limit choices to the choices given.

  A choices list looks like this:

  ```
  YEAR_IN_SCHOOL_CHOICES = [
      ('FR', 'Freshman'),
      ('SO', 'Sophomore'),
      ('JR', 'Junior'),
      ('SR', 'Senior'),
      ('GR', 'Graduate'),
  ]
  ```

  > **Note**
  >
  > A new migration is created each time the order of `choices` changes.

  The first element in each tuple is the value that will be stored in the
  database. The second element is displayed by the field’s form widget.

  Given a model instance, the display value for a field with `choices` can
  be accessed using the [`get_FOO_display()`](/ko/2.2/ref/models/instances/#django.db.models.Model.get_FOO_display)
  method. For example:

  ```
  from django.db import models

  class Person(models.Model):
      SHIRT_SIZES = (
          ('S', 'Small'),
          ('M', 'Medium'),
          ('L', 'Large'),
      )
      name = models.CharField(max_length=60)
      shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
  ```

  ```
  >>> p = Person(name="Fred Flintstone", shirt_size="L")
  >>> p.save()
  >>> p.shirt_size
  'L'
  >>> p.get_shirt_size_display()
  'Large'
  ```

**[`default`](/ko/2.2/ref/models/fields/#django.db.models.Field.default)**

  The default value for the field. This can be a value or a callable
  object. If callable it will be called every time a new object is
  created.

**[`help_text`](/ko/2.2/ref/models/fields/#django.db.models.Field.help_text)**

  Extra “help” text to be displayed with the form widget. It’s useful for
  documentation even if your field isn’t used on a form.

**[`primary_key`](/ko/2.2/ref/models/fields/#django.db.models.Field.primary_key)**

  If `True`, this field is the primary key for the model.

  If you don’t specify [`primary_key=True`](/ko/2.2/ref/models/fields/#django.db.models.Field.primary_key) for
  any fields in your model, Django will automatically add an
  [`IntegerField`](/ko/2.2/ref/models/fields/#django.db.models.IntegerField) to hold the primary key, so you don’t need to set
  [`primary_key=True`](/ko/2.2/ref/models/fields/#django.db.models.Field.primary_key) on any of your fields
  unless you want to override the default primary-key behavior. For more,
  see [Automatic primary key fields](#automatic-primary-key-fields).

  The primary key field is read-only. If you change the value of the primary
  key on an existing object and then save it, a new object will be created
  alongside the old one. For example:

  ```
  from django.db import models

  class Fruit(models.Model):
      name = models.CharField(max_length=100, primary_key=True)
  ```

  ```pycon
  >>> fruit = Fruit.objects.create(name='Apple')
  >>> fruit.name = 'Pear'
  >>> fruit.save()
  >>> Fruit.objects.values_list('name', flat=True)
  <QuerySet ['Apple', 'Pear']>
  ```

**[`unique`](/ko/2.2/ref/models/fields/#django.db.models.Field.unique)**

  If `True`, this field must be unique throughout the table.

Again, these are just short descriptions of the most common field options. Full
details can be found in the [common model field option reference](/ko/2.2/ref/models/fields/#common-model-field-options).

### Automatic primary key fields

By default, Django gives each model the following field:

```
id = models.AutoField(primary_key=True)
```

This is an auto-incrementing primary key.

If you’d like to specify a custom primary key, just specify
[`primary_key=True`](/ko/2.2/ref/models/fields/#django.db.models.Field.primary_key) on one of your fields. If Django
sees you’ve explicitly set [`Field.primary_key`](/ko/2.2/ref/models/fields/#django.db.models.Field.primary_key), it won’t add the automatic
`id` column.

Each model requires exactly one field to have [`primary_key=True`](/ko/2.2/ref/models/fields/#django.db.models.Field.primary_key) (either explicitly declared or automatically added).

### Verbose field names

Each field type, except for [`ForeignKey`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey),
[`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) and
[`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField), takes an optional first positional
argument – a verbose name. If the verbose name isn’t given, Django will
automatically create it using the field’s attribute name, converting underscores
to spaces.

In this example, the verbose name is `"person's first name"`:

```
first_name = models.CharField("person's first name", max_length=30)
```

In this example, the verbose name is `"first name"`:

```
first_name = models.CharField(max_length=30)
```

[`ForeignKey`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey),
[`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) and
[`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) require the first argument to be a
model class, so use the [`verbose_name`](/ko/2.2/ref/models/fields/#django.db.models.Field.verbose_name) keyword argument:

```
poll = models.ForeignKey(
    Poll,
    on_delete=models.CASCADE,
    verbose_name="the related poll",
)
sites = models.ManyToManyField(Site, verbose_name="list of sites")
place = models.OneToOneField(
    Place,
    on_delete=models.CASCADE,
    verbose_name="related place",
)
```

The convention is not to capitalize the first letter of the
[`verbose_name`](/ko/2.2/ref/models/fields/#django.db.models.Field.verbose_name). Django will automatically capitalize the first
letter where it needs to.

### 관계

분명히, 관계형 데이터베이스의 강점은 테이블 상호간의 관계에서 기인 합니다. Django는 주요한 3 가지 데이터베이스 관계: 다대일, 다대다, 일대일을 제공합니다.

#### Many-to-one relationships

다대일 관계를 정의하기 위해 ``django.db.model.ForeignKey`를 사용합니다. 여타 다른 :class:`~django.db.models.Field`` 타입을 사용하듯이 모델에 클래스 속성을 포함시킴으로서 사용합니다.

class:~django.db.models.ForeignKey 는 위치 기반 인자 (인자의 순서가 있는 방식) 로 해당 모델과 관련있는 클래스를 필요로 합니다 (주: 예를 들어 첫번째 인자로 상대 클래스를 명기 해야하는식으로).

예를 들어 `Car` 모델은 한개의 `Manufacturer` (제조사) 을 가지고 있습니다,즉 `Manufacturer` 는 여러개의 `Car` 를 만들 수 있지만 하나의 `Car` 그 자체로는 하나의 `Manufacturer` 만을 갖습니다 - 아래의 정의를 사용하십시오 -

```
from django.db import models

class Manufacturer(models.Model):
    # ...
    pass

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
    # ...
```

또한 되돌림 관계([recursive relationships)](/ko/2.2/ref/models/fields/#recursive-relationships) (자신을 참조하는 다대일 관계를 갖는 오브젝트) 와 아직 다른 모델들과의 관계가 정의되지 않은 관계) \<lazy-relationships\>\`; 참조 [the model field reference](/ko/2.2/ref/models/fields/#ref-foreignkey) 상세설명.

강제하지는 않지만 권고하는 바는 [`ForeignKey`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey) field 의 이름 ( 위의 예제에서는 `manufacturer` 로)  은 모델의 이름을 소문자로 명기하는겁니다. 물론 원하는대로 지을순 있습니다:: 예를 들면:

```
class Car(models.Model):
    company_that_makes_it = models.ForeignKey(
        Manufacturer,
        on_delete=models.CASCADE,
    )
    # ...
```

> **See also**
>
> class:~django.db.models.ForeignKey 필드는 모델 필드를 참조하는 여러가지 많은 인자들을 받아들일 수 있습니다. \<foreign-key-arguments\>이들 옵션들은 그 관계들이 어떻게 작용 할 지 정의 하는데 도움을 줍니다; 모두 선택 사항입니다.
>
> For details on accessing 역방향-관계 오브젝트들을 접근하는 상세한 사항을 볼려면 다음의 예제를 참조하십시오 \<backwards-related-objects\>\`.
>
> 예제 코드를 보려면 :doc:Many-to-one relationship model example\`\</topics/db/examples/many\_to\_one\>를  참조하십시오.

#### Many-to-many relationships

다대다(many-to-many) 관계를 정의하기 위해서는 [`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField). 를 다른  [`Field`](/ko/2.2/ref/models/fields/#django.db.models.Field) type 을 사용하듯이 사용하시오: 모델의 class 속성처럼 그걸 포함 시킴으로써.

[`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) 는 위치 인자 - 모델과 관련있는 class- 를 필요로 합니다:   .

예를들어 만일 `Pizza` 가 여러개의 `Topping` objects 를 갖는다면 , 즉, 하나의 `Topping` 은 여러개의 pizzas 위에 올려질 수 있고 각각의 `Pizza` 또한 여러가지 toppings 을 갖는다면.  – 이것이 그걸 표현하는 겁니다:

```
from django.db import models

class Topping(models.Model):
    # ...
    pass

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)
```

django.db.models.ForeignKey\` 에서, 되돌림 관계(recursive relationships) \<recursive-relationships\>\` ( 자신에 대한 다대다 관계를 갖는 오브젝트) and [relationships to models not yet defined](/ko/2.2/ref/models/fields/#lazy-relationships).

다음은 강제하지는 않지만 권고하는 바 입니다. [`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField)  ( 위의 예제에서는 `toppings` ) 의 이름은 모델 오브젝트들의 관계를 복수(plural) 명사로 명기 하는 것 입니다.

어느 모델에 django.db.models.ManyToManyField\` 를 정의 해야하는것은 상관 없지만 오직 한쪽 - 양쪽 모두가 아닌 - , 모델에만 정의 해야 합니다.

일반적으로, [`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) instances 는 Form 에서 수정 되어질 오브젝트 안으로 위치해야 합니다. 위의 예제에서  `toppings` 들은 `Pizza` 안에 있습니다 ( `Topping` 은 하나의 `pizzas` 을 갖고 있다라기 보다는 [`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) )  그 이유는 “pizza 가 여러 toppings  갖고 있다”  라는 표현이 “하나의 topping 이 여러 pizzas 에 놓여져 있다” 라는 표현 보다 더 자연스러운 생각 이기 때문입니다.

> **See also**
>
> 모든 예제들을 보려면 the [다대다 관계 모델](/ko/2.2/topics/db/examples/many_to_many/)  참조 하세요

[`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) fields also accept a number of
extra arguments which are explained in [the model field reference](/ko/2.2/ref/models/fields/#manytomany-arguments). These options help define how the relationship
should work; all are optional.

#### 다대다 관계에서의 여분의 필드들.

Pizzas 와 toppings 을 섞고 매치 시키는 것과 같은 간단한 다대다 관계를 다루려 할때  표준 클래스인 [`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) 이 필요한 모든 것 입니다. 하지만 때론 두개의 모델간의 관계를 갖게하는 데이타 연관 ( associate ) 이 필요합니다.

For example, consider the case of an application tracking the musical groups
which musicians belong to. There is a many-to-many relationship between a person
and the groups of which they are a member, so you could use a
[`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) to represent this relationship.
However, there is a lot of detail about the membership that you might want to
collect, such as the date at which the person joined the group.

For these situations, Django allows you to specify the model that will be used
to govern the many-to-many relationship. You can then put extra fields on the
intermediate model. The intermediate model is associated with the
[`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) using the
[`through`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField.through) argument to point to the model
that will act as an intermediary. For our musician example, the code would look
something like this:

```
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)
```

When you set up the intermediary model, you explicitly specify foreign
keys to the models that are involved in the many-to-many relationship. This
explicit declaration defines how the two models are related.

임시( intermediate )모델에는 몇가지 제약이 있습니다:

- Your intermediate model must contain one - and *only* one - foreign key
  to the source model (this would be `Group` in our example), or you must
  explicitly specify the foreign keys Django should use for the relationship
  using [`ManyToManyField.through_fields`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField.through_fields).
  If you have more than one foreign key and `through_fields` is not
  specified, a validation error will be raised. A similar restriction applies
  to the foreign key to the target model (this would be `Person` in our
  example).
- For a model which has a many-to-many relationship to itself through an
  intermediary model, two foreign keys to the same model are permitted, but
  they will be treated as the two (different) sides of the many-to-many
  relationship. If there are *more* than two foreign keys though, you
  must also specify `through_fields` as above, or a validation error
  will be raised.
- When defining a many-to-many relationship from a model to
  itself, using an intermediary model, you *must* use
  [`symmetrical=False`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField.symmetrical) (see
  [the model field reference](/ko/2.2/ref/models/fields/#manytomany-arguments)).

Now that you have set up your [`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) to use
your intermediary model (`Membership`, in this case), you’re ready to start
creating some many-to-many relationships. You do this by creating instances of
the intermediate model:

```
>>> ringo = Person.objects.create(name="Ringo Starr")
>>> paul = Person.objects.create(name="Paul McCartney")
>>> beatles = Group.objects.create(name="The Beatles")
>>> m1 = Membership(person=ringo, group=beatles,
...     date_joined=date(1962, 8, 16),
...     invite_reason="Needed a new drummer.")
>>> m1.save()
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>]>
>>> ringo.group_set.all()
<QuerySet [<Group: The Beatles>]>
>>> m2 = Membership.objects.create(person=paul, group=beatles,
...     date_joined=date(1960, 8, 1),
...     invite_reason="Wanted to form a band.")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>]>
```

You can also use `add()`, `create()`, or `set()` to create relationships,
as long as you specify `through_defaults` for any required fields:

```
>>> beatles.members.add(john, through_defaults={'date_joined': date(1960, 8, 1)})
>>> beatles.members.create(name="George Harrison", through_defaults={'date_joined': date(1960, 8, 1)})
>>> beatles.members.set([john, paul, ringo, george], through_defaults={'date_joined': date(1960, 8, 1)})
```

You may prefer to create instances of the intermediate model directly.

If the custom through table defined by the intermediate model does not enforce
uniqueness on the `(model1, model2)` pair, allowing multiple values, the
[`remove()`](/ko/2.2/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove) call will
remove all intermediate model instances:

```
>>> Membership.objects.create(person=ringo, group=beatles,
...     date_joined=date(1968, 9, 4),
...     invite_reason="You've been gone for a month and we miss you.")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>, <Person: Ringo Starr>]>
>>> # This deletes both of the intermediate model instances for Ringo Starr
>>> beatles.members.remove(ringo)
>>> beatles.members.all()
<QuerySet [<Person: Paul McCartney>]>
```

The [`clear()`](/ko/2.2/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear)
method can be used to remove all many-to-many relationships for an instance:

```
>>> # Beatles have broken up
>>> beatles.members.clear()
>>> # Note that this deletes the intermediate model instances
>>> Membership.objects.all()
<QuerySet []>
```

Once you have established the many-to-many relationships, you can issue
queries. Just as with normal many-to-many relationships, you can query using
the attributes of the many-to-many-related model:

```
# Find all the groups with a member whose name starts with 'Paul'
>>> Group.objects.filter(members__name__startswith='Paul')
<QuerySet [<Group: The Beatles>]>
```

As you are using an intermediate model, you can also query on its attributes:

```
# Find all the members of the Beatles that joined after 1 Jan 1961
>>> Person.objects.filter(
...     group__name='The Beatles',
...     membership__date_joined__gt=date(1961,1,1))
<QuerySet [<Person: Ringo Starr]>
```

If you need to access a membership’s information you may do so by directly
querying the `Membership` model:

```
>>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'
```

Another way to access the same information is by querying the
[many-to-many reverse relationship](/ko/2.2/topics/db/queries/#m2m-reverse-relationships) from a
`Person` object:

```
>>> ringos_membership = ringo.membership_set.get(group=beatles)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'
```

#### One-to-one relationships

To define a one-to-one relationship, use
[`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField). You use it just like any other
`Field` type: by including it as a class attribute of your model.

This is most useful on the primary key of an object when that object “extends”
another object in some way.

[`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) requires a positional argument: the
class to which the model is related.

For example, if you were building a database of “places”, you would
build pretty standard stuff such as address, phone number, etc. in the
database. Then, if you wanted to build a database of restaurants on
top of the places, instead of repeating yourself and replicating those
fields in the `Restaurant` model, you could make `Restaurant` have
a [`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) to `Place` (because a
restaurant “is a” place; in fact, to handle this you’d typically use
[inheritance](#model-inheritance), which involves an implicit
one-to-one relation).

As with [`ForeignKey`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey), a [recursive relationship](/ko/2.2/ref/models/fields/#recursive-relationships) can be defined and [references to as-yet
undefined models](/ko/2.2/ref/models/fields/#lazy-relationships) can be made.

> **See also**
>
> See the [One-to-one relationship model example](/ko/2.2/topics/db/examples/one_to_one/) for a full example.

[`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) fields also accept an optional
[`parent_link`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField.parent_link) argument.

[`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) classes used to automatically become
the primary key on a model. This is no longer true (although you can manually
pass in the [`primary_key`](/ko/2.2/ref/models/fields/#django.db.models.Field.primary_key) argument if you like).
Thus, it’s now possible to have multiple fields of type
[`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) on a single model.

### Models across files

It’s perfectly OK to relate a model to one from another app. To do this, import
the related model at the top of the file where your model is defined. Then,
just refer to the other model class wherever needed. For example:

```
from django.db import models
from geography.models import ZipCode

class Restaurant(models.Model):
    # ...
    zip_code = models.ForeignKey(
        ZipCode,
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
    )
```

### 필드 이름 제약

Django는 모델 필드 이름에 몇 가지 제약을 두고 있습니다.

1. 필드 이름은 파이썬 예약어로 만들 수 없습니다. 왜냐하면 파이썬 문법 에러를 발생시키기 때문입니다. 예를 들어:

   ```
   class Example(models.Model):
       pass = models.IntegerField() # 'pass' is a reserved word!
   ```
2. Django의 쿼리 조회 문법과 비슷해 보일 수 있기에 필드 이름은 하나 이상의 underscore를 포함해선 안됩니다. 예를 들어:

   ```
   class Example(models.Model):
       foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
   ```
3. 비슷한 이유로 필드 이름은 undersocre로 끝날 수 없습니다.

These limitations can be worked around, though, because your field name doesn’t
necessarily have to match your database column name. See the
[`db_column`](/ko/2.2/ref/models/fields/#django.db.models.Field.db_column) option.

SQL reserved words, such as `join`, `where` or `select`, *are* allowed as
model field names, because Django escapes all database table names and column
names in every underlying SQL query. It uses the quoting syntax of your
particular database engine.

### Custom field types

If one of the existing model fields cannot be used to fit your purposes, or if
you wish to take advantage of some less common database column types, you can
create your own field class. Full coverage of creating your own fields is
provided in [Writing custom model fields](/ko/2.2/howto/custom-model-fields/).

## `Meta` options

Give your model metadata by using an inner `class Meta`, like so:

```
from django.db import models

class Ox(models.Model):
    horn_length = models.IntegerField()

    class Meta:
        ordering = ["horn_length"]
        verbose_name_plural = "oxen"
```

Model metadata is “anything that’s not a field”, such as ordering options
([`ordering`](/ko/2.2/ref/models/options/#django.db.models.Options.ordering)), database table name ([`db_table`](/ko/2.2/ref/models/options/#django.db.models.Options.db_table)), or
human-readable singular and plural names ([`verbose_name`](/ko/2.2/ref/models/options/#django.db.models.Options.verbose_name) and
[`verbose_name_plural`](/ko/2.2/ref/models/options/#django.db.models.Options.verbose_name_plural)). None are required, and adding `class
Meta` to a model is completely optional.

A complete list of all possible `Meta` options can be found in the [model
option reference](/ko/2.2/ref/models/options/).

## 모델 속성

**`objects`**

  The most important attribute of a model is the
  [`Manager`](/ko/2.2/topics/db/managers/#django.db.models.Manager). It’s the interface through which
  database query operations are provided to Django models and is used to
  [retrieve the instances](/ko/2.2/topics/db/queries/#retrieving-objects) from the database. If no
  custom `Manager` is defined, the default name is
  [`objects`](/ko/2.2/ref/models/class/#django.db.models.Model.objects). Managers are only accessible via
  model classes, not the model instances.

## 모델 메소드

Define custom methods on a model to add custom “row-level” functionality to your
objects. Whereas [`Manager`](/ko/2.2/topics/db/managers/#django.db.models.Manager) methods are intended to do
“table-wide” things, model methods should act on a particular model instance.

This is a valuable technique for keeping business logic in one place – the
model.

예를 들어, 이 모델은 몇 가지 커스텀 메소드를 가지고 있습니다:

```
from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()

    def baby_boomer_status(self):
        "Returns the person's baby-boomer status."
        import datetime
        if self.birth_date < datetime.date(1945, 8, 1):
            return "Pre-boomer"
        elif self.birth_date < datetime.date(1965, 1, 1):
            return "Baby boomer"
        else:
            return "Post-boomer"

    @property
    def full_name(self):
        "Returns the person's full name."
        return '%s %s' % (self.first_name, self.last_name)
```

The last method in this example is a [property](/ko/2.2/glossary/#term-property).

The [model instance reference](/ko/2.2/ref/models/instances/) has a complete list
of [methods automatically given to each model](/ko/2.2/ref/models/instances/#model-instance-methods).
You can override most of these – see [overriding predefined model methods](#overriding-predefined-model-methods),
below – but there are a couple that you’ll almost always want to define:

**[`__str__()`](/ko/2.2/ref/models/instances/#django.db.models.Model.__str__)**

  A Python “magic method” that returns a string representation of any
  object. This is what Python and Django will use whenever a model
  instance needs to be coerced and displayed as a plain string. Most
  notably, this happens when you display an object in an interactive
  console or in the admin.

  You’ll always want to define this method; the default isn’t very helpful
  at all.

**[`get_absolute_url()`](/ko/2.2/ref/models/instances/#django.db.models.Model.get_absolute_url)**

  This tells Django how to calculate the URL for an object. Django uses
  this in its admin interface, and any time it needs to figure out a URL
  for an object.

  Any object that has a URL that uniquely identifies it should define this
  method.

### Overriding predefined model methods

There’s another set of [model methods](/ko/2.2/ref/models/instances/#model-instance-methods) that
encapsulate a bunch of database behavior that you’ll want to customize. In
particular you’ll often want to change the way [`save()`](/ko/2.2/ref/models/instances/#django.db.models.Model.save) and
[`delete()`](/ko/2.2/ref/models/instances/#django.db.models.Model.delete) work.

You’re free to override these methods (and any other model method) to alter
behavior.

A classic use-case for overriding the built-in methods is if you want something
to happen whenever you save an object. For example (see
[`save()`](/ko/2.2/ref/models/instances/#django.db.models.Model.save) for documentation of the parameters it accepts):

```
from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def save(self, *args, **kwargs):
        do_something()
        super().save(*args, **kwargs)  # Call the "real" save() method.
        do_something_else()
```

당신은 저장하는 걸 막을 수도 있습니다.

```
from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def save(self, *args, **kwargs):
        if self.name == "Yoko Ono's blog":
            return # Yoko shall never have her own blog!
        else:
            super().save(*args, **kwargs)  # Call the "real" save() method.
```

It’s important to remember to call the superclass method – that’s
that `super().save(*args, **kwargs)` business – to ensure
that the object still gets saved into the database. If you forget to
call the superclass method, the default behavior won’t happen and the
database won’t get touched.

It’s also important that you pass through the arguments that can be
passed to the model method – that’s what the `*args, **kwargs` bit
does. Django will, from time to time, extend the capabilities of
built-in model methods, adding new arguments. If you use `*args,
**kwargs` in your method definitions, you are guaranteed that your
code will automatically support those arguments when they are added.

> **Overridden model methods are not called on bulk operations**
>
> Note that the [`delete()`](/ko/2.2/ref/models/instances/#django.db.models.Model.delete) method for an object is not
> necessarily called when [deleting objects in bulk using a
> QuerySet](/ko/2.2/topics/db/queries/#topics-db-queries-delete) or as a result of a [`cascading
> delete`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.on_delete). To ensure customized
> delete logic gets executed, you can use
> [`pre_delete`](/ko/2.2/ref/signals/#django.db.models.signals.pre_delete) and/or
> [`post_delete`](/ko/2.2/ref/signals/#django.db.models.signals.post_delete) signals.
>
> Unfortunately, there isn’t a workaround when
> [`creating`](/ko/2.2/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create) or
> [`updating`](/ko/2.2/ref/models/querysets/#django.db.models.query.QuerySet.update) objects in bulk,
> since none of [`save()`](/ko/2.2/ref/models/instances/#django.db.models.Model.save),
> [`pre_save`](/ko/2.2/ref/signals/#django.db.models.signals.pre_save), and
> [`post_save`](/ko/2.2/ref/signals/#django.db.models.signals.post_save) are called.

### 커스텀 SQL을 실행

Another common pattern is writing custom SQL statements in model methods and
module-level methods. For more details on using raw SQL, see the documentation
on [using raw SQL](/ko/2.2/topics/db/sql/).

## 모델 상속

Model inheritance in Django works almost identically to the way normal
class inheritance works in Python, but the basics at the beginning of the page
should still be followed. That means the base class should subclass
[`django.db.models.Model`](/ko/2.2/ref/models/instances/#django.db.models.Model).

The only decision you have to make is whether you want the parent models to be
models in their own right (with their own database tables), or if the parents
are just holders of common information that will only be visible through the
child models.

Django에서 가능한 상속의 3가지 스타일이 있다.

1. Often, you will just want to use the parent class to hold information that
   you don’t want to have to type out for each child model. This class isn’t
   going to ever be used in isolation, so [추상 기반 클래스](#abstract-base-classes) are
   what you’re after.
2. If you’re subclassing an existing model (perhaps something from another
   application entirely) and want each model to have its own database table,
   [다중 테이블 상속](#multi-table-inheritance) is the way to go.
3. Finally, if you only want to modify the Python-level behavior of a model,
   without changing the models fields in any way, you can use
   [대리 모델 (Proxy Model )](#proxy-models).

### 추상 기반 클래스

Abstract base classes are useful when you want to put some common
information into a number of other models. You write your base class
and put `abstract=True` in the [Meta](#meta-options)
class. This model will then not be used to create any database
table. Instead, when it is used as a base class for other models, its
fields will be added to those of the child class.

예제:

```
from django.db import models

class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

    class Meta:
        abstract = True

class Student(CommonInfo):
    home_group = models.CharField(max_length=5)
```

The `Student` model will have three fields: `name`, `age` and
`home_group`. The `CommonInfo` model cannot be used as a normal Django
model, since it is an abstract base class. It does not generate a database
table or have a manager, and cannot be instantiated or saved directly.

추상 기반 클래스로부터 상속된 필드는 다른 필드나 값으로 오버라이드 될 수 있습니다 혹은 “None”으로 제거될 수 있습니다.

For many uses, this type of model inheritance will be exactly what you want.
It provides a way to factor out common information at the Python level, while
still only creating one database table per child model at the database level.

#### “Meta” 상속

When an abstract base class is created, Django makes any [Meta](#meta-options)
inner class you declared in the base class available as an
attribute. If a child class does not declare its own [Meta](#meta-options)
class, it will inherit the parent’s [Meta](#meta-options). If the child wants to
extend the parent’s [Meta](#meta-options) class, it can subclass it. For example:

```
from django.db import models

class CommonInfo(models.Model):
    # ...
    class Meta:
        abstract = True
        ordering = ['name']

class Student(CommonInfo):
    # ...
    class Meta(CommonInfo.Meta):
        db_table = 'student_info'
```

Django does make one adjustment to the [Meta](#meta-options) class of an abstract base
class: before installing the [Meta](#meta-options) attribute, it sets `abstract=False`.
This means that children of abstract base classes don’t automatically become
abstract classes themselves. Of course, you can make an abstract base class
that inherits from another abstract base class. You just need to remember to
explicitly set `abstract=True` each time.

Some attributes won’t make sense to include in the [Meta](#meta-options) class of an
abstract base class. For example, including `db_table` would mean that all
the child classes (the ones that don’t specify their own [Meta](#meta-options)) would use
the same database table, which is almost certainly not what you want.

#### “related\_name”와 “related\_query\_name”은 주의하세요.

If you are using [`related_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_name) or
[`related_query_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_query_name) on a `ForeignKey` or
`ManyToManyField`, you must always specify a *unique* reverse name and query
name for the field. This would normally cause a problem in abstract base
classes, since the fields on this class are included into each of the child
classes, with exactly the same values for the attributes (including
[`related_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_name) and
[`related_query_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_query_name)) each time.

To work around this problem, when you are using
[`related_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_name) or
[`related_query_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_query_name) in an abstract base
class (only), part of the value should contain `'%(app_label)s'` and
`'%(class)s'`.

- `'%(class)s'` is replaced by the lowercased name of the child class that
  the field is used in.
- `'%(app_label)s'` is replaced by the lowercased name of the app the child
  class is contained within. Each installed application name must be unique and
  the model class names within each app must also be unique, therefore the
  resulting name will end up being different.

For example, given an app `common/models.py`:

```
from django.db import models

class Base(models.Model):
    m2m = models.ManyToManyField(
        OtherModel,
        related_name="%(app_label)s_%(class)s_related",
        related_query_name="%(app_label)s_%(class)ss",
    )

    class Meta:
        abstract = True

class ChildA(Base):
    pass

class ChildB(Base):
    pass
```

Along with another app `rare/models.py`:

```
from common.models import Base

class ChildB(Base):
    pass
```

The reverse name of the `common.ChildA.m2m` field will be
`common_childa_related` and the reverse query name will be `common_childas`.
The reverse name of the `common.ChildB.m2m` field will be
`common_childb_related` and the reverse query name will be
`common_childbs`. Finally, the reverse name of the `rare.ChildB.m2m` field
will be `rare_childb_related` and the reverse query name will be
`rare_childbs`. It’s up to you how you use the `'%(class)s'` and
`'%(app_label)s'` portion to construct your related name or related query name
but if you forget to use it, Django will raise errors when you perform system
checks (or run [`migrate`](/ko/2.2/ref/django-admin/#django-admin-migrate)).

If you don’t specify a [`related_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_name)
attribute for a field in an abstract base class, the default reverse name will
be the name of the child class followed by `'_set'`, just as it normally
would be if you’d declared the field directly on the child class. For example,
in the above code, if the [`related_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_name)
attribute was omitted, the reverse name for the `m2m` field would be
`childa_set` in the `ChildA` case and `childb_set` for the `ChildB`
field.

### 다중 테이블 상속

The second type of model inheritance supported by Django is when each model in
the hierarchy is a model all by itself. Each model corresponds to its own
database table and can be queried and created individually. The inheritance
relationship introduces links between the child model and each of its parents
(via an automatically-created [`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField)).
For example:

```
from django.db import models

class Place(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

class Restaurant(Place):
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)
```

`Place` 의 모든 필드들은 `Restaurant` 에서 사용 가능합니다, 비록 그들 데이타가 각각 다른 테이블에 존재함에도 불구하고. 자 두 개의 가능성이 있습니다:

```
>>> Place.objects.filter(name="Bob's Cafe")
>>> Restaurant.objects.filter(name="Bob's Cafe")
```

If you have a `Place` that is also a `Restaurant`, you can get from the
`Place` object to the `Restaurant` object by using the lowercase version of
the model name:

```
>>> p = Place.objects.get(id=12)
# If p is a Restaurant object, this will give the child class:
>>> p.restaurant
<Restaurant: ...>
```

하지만, 위의 예제에서 `p` 변수는 `Restaurant` 이 아니었습니다.  ( 그것은 직접 `Place` object 로써 생성이 되었었거나혹은 다른 클래스의 부모 클래스로서 만들어 진것입니다) 그래서 `p.restaurant` 은 `Restaurant.DoesNotExist` 예외를 만들어 낼 겁니다.

`Restaurant` 에 자동적으로생성이 된  [`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField)  의 `Place` 로의 연결이 이것 처럼 보입니다:

```
place_ptr = models.OneToOneField(
    Place, on_delete=models.CASCADE,
    parent_link=True,
)
```

[`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) 에   [`parent_link=True`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField.parent_link) on `Restaurant` 속성을 주어 정의한 필드를 덮어쓰기(override) 할 수 있습니다..

#### `Meta` 그리고 다중 테이블 상속

다중 테이블 상속시 자식 클래스가 부모 클래스의 [Meta](#meta-options) class. 를 상속 받는다는건 모순 입니다. 모든 [Meta](#meta-options) 옵션들은 이미 부모 클래스에 적용되어져 있고그들을 자식 클래스에서 다시 적용한다는건 대개의 경우 모순되는 행동 (contradictory behavior) 만 만들어 낼 개연성이 높습니다.  ( 이건 추상화 클래스 용례 - 기저 클래스(base class) 가 그 자체의 권리 안에 존재 하지 않는) 에 반하는 행위.)

그리하여 자식 모델이 부모 모델의 [Meta](#meta-options) class 에 접근 하지 않게 됩니다.. 하지만 제한적이나마 잘 사용하지 않는 사례 (자식이 부모의 행동 ( behavior ) 을 상속받는) 가 있습니다: 만일 자식이 [`ordering`](/ko/2.2/ref/models/options/#django.db.models.Options.ordering) 속성이나  [`get_latest_by`](/ko/2.2/ref/models/options/#django.db.models.Options.get_latest_by) 속성을 사용하지 않았다면 자식은 이러한 것 들을 부모로 부터 상속 받을 겁니다.

만일 부모가 순서(ordering) 을 갖고 있고 당신은 자식 클래스가 그 어느 ordering 을 갖는걸 원치 않는다면 명확히 그걸 “불가(disable)” 하다고 명기 명기 할 수 있습니다:

```
class ChildModel(ParentModel):
    # ...
    class Meta:
        # Remove parent's ordering effect
        ordering = []
```

#### 상속과 역관계

다중 테이블 상속은 암묵적(밖으로 명확히 표현하지 아니한)으로  [`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) 를 사용해서 자식과 부모를 연결 하기 때문에 , 부모로부터 자식으로의 이동 (move? 주: 여기서는 access 가 맞을듯)  가능성이 위의 예제에서 처럼 존재 합니다. 하지만 이것은 이름을 부여하므로서 - default 로  value for [`ForeignKey`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey) 와  [`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField) relations 에 대한  [`related_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_name)  값을 줌으로서 - 사용 되어 집니다.  만일 이러한 관계 타입의 부모의 subclass 로서 사용할려면 당신은 명확히 [`related_name`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey.related_name) 속성을 각각의 해당 필드에 선언 해 주어야 합니다. 만일 선언해주지 않으면 장고는  유효성검사 (validation) 에러를 만들 겁니다.

예를 들어, 위의 `Place` class 를 다시 사용해서 [`ManyToManyField`](/ko/2.2/ref/models/fields/#django.db.models.ManyToManyField):: 관계를 갖는 다른 subclass 를 만들어 봅시다

```
class Supplier(Place):
    customers = models.ManyToManyField(Place)
```

결과는 오류를 나타낼 겁니다

```
Reverse query name for 'Supplier.customers' clashes with reverse query
name for 'Supplier.place_ptr'.

HINT: Add or change a related_name argument to the definition for
'Supplier.customers' or 'Supplier.place_ptr'.
```

`customers` field 에 대한  `related_name` 을 아래와 같이 추가 함으로써 그 오류는 사라질 겁니다: `models.ManyToManyField(Place, related_name='provider')`.

#### 부모 연결 필드를 명기하기

앞서 언급했듯이, 장고는 자동적으로 [`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) 를 만들어서 자식 클래스가 부모 클래스로 연결이 되도록 합니다. 만일 그 부모로의 연결 속성에 대한 이름을 제컨트롤 하고자 한다면 [`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) 에  [`parent_link=True 라는 속성을 세팅하여 생성 할 수 있습니다.`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField.parent_link) 는 해당 필드가 부모 클래스로의 연결 되었다는것을 표시 한 것 입니다.

### 대리 모델 (Proxy Model )

다중 테이블 상속을 사용하면  \<multi-table-inheritance\>\`, 하나의 새로운 데이타베이스 테이블이 어느 모델의 각각의 subclass 로서 생성이 된 것 입니다. 이건 보통의 경우 바람직한 행위 입니다, 그 subclass 가  base class 에는 없는 새로운 필드를 추가 하기 전까지는. 하지만 가끔은 Python 의 모델에 대한 행위(behavior) 를 바꾸고자 할 때가 있습니다. - 아마도 default manager 를 변경하거나 새로운 매써드를 추가 하면서요.

이것이 바로 “대리 모델 상속”이 존재하는 목적 입니다: 오리지널 모델에 대한 대리자를 만듦으로서. 대리 모델의 인스턴스를 만들고 없애고 수정할 수 있고 마치 오리지널 모델이 하는것처럼 그 대리 모델이 데이터를 저장도 할 수 있습니다.

대리 모델들(Proxy models) 은 보통의 모델들 처럼 선언 됩니다. 단지  `Meta` class 의 [`proxy`](/ko/2.2/ref/models/options/#django.db.models.Options.proxy) 속성에 `True` 값을 세팅 해 줌으로써 장고에게  “이건 대리 모델 이야!” 라고 말하는 겁니다.

예를 들어, `Person` 모델에 한 매써드를 추가하고자 한다고 가정해보면. 다음과 같이 할 수 있습니다:

```
from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

class MyPerson(Person):
    class Meta:
        proxy = True

    def do_something(self):
        # ...
        pass
```

`MyPerson` 클래스는 부모 클래스인 `Person` 처럼 동일한  데이타베이스 테이블에 작동 됩니다. 또한 특별히, 어느 새로운 `Person` 의 인스턴스는 MyPerson\`\`을 통해 접근 가능하고 기타 여러가지 기능이 가능하게 됩니다:

```
>>> p = Person.objects.create(first_name="foobar")
>>> MyPerson.objects.get(first_name="foobar")
<MyPerson: foobar>
```

대리 모델을 통해 오리저널 모델이 갖는 순서(ordering) 와는 다른 순서를 갖도록 할 수도 있습니다. 항상  `Person` model, 이 갖는 순서를 원하지 않을수도 있습니다. 하지만 대리 모델 을 이용하면 정기적으로 `last_name` 순서를 갖게 만들수도 있습니다. 쉽죠:

```
class OrderedPerson(Person):
    class Meta:
        ordering = ["last_name"]
        proxy = True
```

지금 보통 `Person` 에 대한 질의는 순서가 없을 겁니다. 그리고 `OrderedPerson` 에 대한 질의는 last\_name\`\`으로 순서화 될 것 입니다.

대리 모델은 다른 모델들과 같은 방법으로 `Meta` attributes :ref:\` 상속을 받습니다 \<meta-and-multi-table-inheritance\>\`.

#### `QuerySet` 은 여전히 요청이 된(requested) 모델들을 반환 합니다.

There is no way to have Django return, say, a `MyPerson` object whenever you
query for `Person` objects. A queryset for `Person` objects will return
those types of objects. The whole point of proxy objects is that code relying
on the original `Person` will use those and your own code can use the
extensions you included (that no other code is relying on anyway). It is not
a way to replace the `Person` (or any other) model everywhere with something
of your own creation.

#### 베이스 (부모) 클래스 제한 사항

대리 모델은 오직 하나의 비추상화(non-abstract) 모델 클래스로부터만 상속을 받습니다. 여러개의 비추상화 모델 클래스들로부터 상속 받아 다른 테이블의 행 (rows) 들 사이의 연결을 제공 할 수 없습니다.  대리 모델은 어느 모델의 필드를 선언 하지 않음으로써 여러 추상화 클래스로부터 다중 상속을 받을수 있습니다.  프록시 모델은 또한 공통의 비추상화 부모 클래스를 공유하는( share a common non-abstract parent class) 여러 프록시 모델로부터 상속을 받을 수도 있습니다.

#### 프록시 모델 (대리 모델) 매니저

프록시 모델에 특정한 모델 매니져를 명기 하지 않는다면  부모 모델의 매니저를 상속 받게 됩니다. 만일 프록시 모델에 매니저를 명기 한다면 그 매니저가 디폴트 매니저가 되어 작동됩니다. 여전히 부모 클래스의 매니저가 사용 가능한 상태 임에도 불구하고요.

위의 예제에 이어서, 당신은 `Person` 모델에 다음처럼 질의를 하면서 디폴트 매니저를 바꾸어 사용 할 수 있습니다:

```
from django.db import models

class NewManager(models.Manager):
    # ...
    pass

class MyPerson(Person):
    objects = NewManager()

    class Meta:
        proxy = True
```

만일 프록시 모델에 새 매니저를 추가하고자 한다면 - 이미 존재하는 디폴트 매니저를 교체하지 않고-.,  [custom manager](/ko/2.2/topics/db/managers/#custom-managers-and-inheritance) 문서에 명기된 테크닉을 이용해서  새로운 매니저를 갖는 베이스 클래스를 만들고 그 프라이머리 베이스 클래스를 상속 하게 할 수 있습니다:

```
# Create an abstract class for the new manager.
class ExtraManagers(models.Model):
    secondary = NewManager()

    class Meta:
        abstract = True

class MyPerson(Person, ExtraManagers):
    class Meta:
        proxy = True
```

이것을 자주 할 필요는 없을지 모르지만 하고자 하면 가능합니다.

#### 프록시 상속과 unmanaged 모델의 차이

프록시 모델 상속은  모델의 `Meta` 클래스에 class:attr:~django.db.models.Options.managed  속성을 부여 하여 매니저 없는 (unmanaged) 모델을 만드는것과 꽤나 비슷하게 보입니다.

주의를 기울여서  [`Meta.db_table`](/ko/2.2/ref/models/options/#django.db.models.Options.db_table) 라고 세팅함으로써 존재하는 모델을 숨기는(shadows)  무-매니저 (unmanaged) 모델을 만들고 파이썬 매써드를 이용하여 그것을 대신하게 할 수 있습니다. 하지만 그건 매우 반복적이고 오류가 나기쉽습니다 fragile ) 마치 어떤 수정을 하게 될 경우 양쪽 모두 동기(synchronized ) 를 위한 복사를 해야 하기 때문입니다.

다른 한 편으로, 프록시 모델은 정확히 오리지널 모델을 대신하는 역할을 하도록 의도 되었습니다. 프록시 모델은 부모 모델의 필드와 매니저들을 직접 상속 받아서 항상 부모 모델과의 동기화를 유지 합니다.

일반적인 규칙:

1. 만일 현존하는 모델이나 테이블을 미러링(모든 변화를 일치 시키는) 하거나  테이블의 모든 열(칼럼) 의 사용을 원치 않을 경우엔  `Meta.managed=False` 를 사용 하시오. 이 옵션은 보통은 모델링 데이타베이스 뷰와 테이블이 장고의 제어 하에 두지 않도록 하는데 유용 합니다.
2. 만일 모델의 Python-only 행위를 변경하고자 하면 , 하지만 모든 필드들을 오리지널 모델에서의 필드들 처럼 유지 하고자 한다면  `Meta.proxy=True`. 를 사용하시오. 이것을 세팅 함으로써 프록시 모델은 데이타가 저장될때  오지지널 모델의 저장 구조와 정확히 일치하는 복사본이 되도록 합니다.

### 다중 상속

Python’s subclassing 과 동일하게, Django model 또한 여러 부모 모델로부터 의 다중 상속이 가능합니다.  보통의 Python 이름 해석( name resolution) 규칙이 적용됨을 명심 하십시오. 첫번째 Base class 안에 보여지는 특별한 이름 (예 [Meta](#meta-options)) 이 사용되어질 하나 입니다(주: 첫번째 베이스 클래스에 선언된 Meta class 만이 사용된다는 의미) : 예를 들어 이는 여러 부모들 각각 [Meta](#meta-options) class 를 갖고 있다면 , 오직 첫번째 것만이 사용되어 집니다. 그외 다른 것들은 무시되어 집니다.

대개, 다중 상속이 필요 치는 않습니다. “mix-in” class 에 주로 유용합니다:  “mix-in” class 를 상속 받는 모든 class 에 특별한 여분의 필드나 매써드를 추가 한다던지. 가급적 상속의 계층구조를 단순하고 직관적이 되도록 유지 하도록 하십시오. 그리하여 이상한 정보 조각이 어디서 부터 흘러 나왔는지 찾는데 고생하지 마십시오.

공통적인   `id` 프라이머리 키를 갖는 다중 상속시 오류가 발생 함에 주의 하십시오. 적절하게 다중 상속을 활용 할려면, 명확하게  [`AutoField`](/ko/2.2/ref/models/fields/#django.db.models.AutoField) 를 base models 에 사용해야 합니다:

```
class Article(models.Model):
    article_id = models.AutoField(primary_key=True)
    ...

class Book(models.Model):
    book_id = models.AutoField(primary_key=True)
    ...

class BookReview(Book, Article):
    pass
```

혹은 [`AutoField`](/ko/2.2/ref/models/fields/#django.db.models.AutoField) 를 갖는 공통의 조상 모델을 사용 하십시오. 이를 위해서 명확하게 각각의 부모 모델에서 공통의 조상 모델로의 [`OneToOneField`](/ko/2.2/ref/models/fields/#django.db.models.OneToOneField) 를 선언하여 자식 모델에 상속되는 자동 생성 되는 필드들 간의 충돌을 피하십시오.:

```
class Piece(models.Model):
    pass

class Article(Piece):
    article_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
    ...

class Book(Piece):
    book_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
    ...

class BookReview(Book, Article):
    pass
```

### 필드이름으로써 “hiding” 은 사용 할 수 없습니다

보통 파이썬의 클래스 상속에 있어서 자식 클래스는 부모 클래스의 어떤 속성이라도 덮어쓰기(override) 할 수 있습니다. 하지만 장고에서는 이것은 대개 모델 필드들에 대해서는 하용 되지 않습니다. 만일 비-추상화 베이스 모델 클래스에 `author` 라는 필드가 있다 칩시다. 그 베이스 클래스를 상속받는 자식 클래스에서 `author` 필드를 재 선언 할 수 없습니다.

이러한 제한은 추상화 클래스로부터 상속을 받았다면  효력이 없게 됩니다. 그러한 필드는 아마도 다른 필드 혹은 값에 의해 overridden 되거나 field\_name = None \`\` 으로 세팅 함으로써 제거 될 수 있습니다.

> **Warning**
>
> 모델 매니저는 추상화 base class 들 로부터 상속이 됩니다. [`Manager`](/ko/2.2/topics/db/managers/#django.db.models.Manager) 를 상속받아 그에 속한 필드를 Overriding 하는건 미묘한 버그를 만들어 낼 수 있습니다. . 참조 [커스텀 매니저와 모델 상속](/ko/2.2/topics/db/managers/#custom-managers-and-inheritance).

> **Note**
>
> 모델에서 특정 필드는 여분의 속성을 정의 합니다, 예를 들어  [`ForeignKey`](/ko/2.2/ref/models/fields/#django.db.models.ForeignKey) 속성은 필드 이름에 “\_id” 를 붙이고, 또한,  참조(foreign) 모델에 대한 `related_name` 과  `related_query_name` 를 정의 할 수 있습니다.
>
> 이들 여분의 속성들은 해당 필드 자체가 변경 되었거나 제거 되어서 더 이상 여분의 속성에 대한 선언이 사라지게 되지 않는한 overridden 되지 않습니다.

부모 모델에 속한 필드에 대한 overriding 은 새로운 인스턴스 초기화(  `Model.__init__` 함수에서 어떤 필드를 초기화 할 것인가?) 하거나 직렬화 ( serialization ) 시에 어려움을 자아 낼 수 있습니다.  이러한 것들은 보통의 파이썬 클래스 상속과비슷한 방식으로 다루어 질 필요가 없는 특성 입니다. 그래서 장고 모델들간의 상속과 파이썬 클래스들간의 상속의 차이가 불규칙적이지 않습니다 (일관성이 있다는 의미).

이러한 제한은 오직  [`Field`](/ko/2.2/ref/models/fields/#django.db.models.Field) 인스턴스인 속성에만 적용 됩니다. 보통의 파이썬 속성은 원하면 overridden 될 수 있습니다. 또한 그 제한은 파이썬이 그것을 알아차렸을때 그 속성의 이름에게 적용만 됩니다(It also only applies to the name of the attribute as Python sees it:) :  만일 수동( manually)  으로 데이터베이스의 컬럼 이름을 명기 하였다면 자식 모델과 조상 모델 각각 동일한 이름을 갖는 컬럼이 있게 됩니다( 두개의 다른 데이터베이스 테이블에 칼럼들이 존재하게 되는)

장고는 조상 모델에 대한 어떤 overriding 에 대해  [`FieldError`](/ko/2.2/ref/exceptions/#django.core.exceptions.FieldError)  를 발생 시킬 겁니다

## 패키지 안에 모델을 조직화하기

[`manage.py startapp`](/ko/2.2/ref/django-admin/#django-admin-startapp) 명령은 `models.py` 화일을 포함하는 application structure 를 만들어 냅니다.만일 모델들이 많다면 그들을 따로이 분리된 화일로 나누어 구성하는것이 유용합니다.

모델에 대한 패키지를 만들기 위해서,  `models.py` 를 제거하고 `myapp/models/` 디렉토리를 만들고 `__init__.py` file 을 만들어 그 화일이 모델들을 저장 하게끔 합니다.  `__init__.py` 화일에서 여러 모델들을 import 해야 합니다..

예를들어 `organic.py` 와 `synthetic.py`  이  `models` 디렉토리에 있다고 하면:

*myapp/models/\_\_init\_\_.py 에*

```python
from .organic import Person
from .synthetic import Robot
```

Explicitly importing each model rather than using `from .models import *`
has the advantages of not cluttering the namespace, making code more readable,
and keeping code analysis tools useful.

> **See also**
>
> **[모델에 관한 문서](/ko/2.2/ref/models/)**
>
>   Covers all the model related APIs including model fields, related
>   objects, and `QuerySet`.
