人の ID が存在しない場合は、Person のようなモデル オブジェクトを作成するか、その人物オブジェクトを取得します。
新しい人物を作成するコードは次のとおりです。
class Person(models.Model):
identifier = models.CharField(max_length = 10)
name = models.CharField(max_length = 20)
objects = PersonManager()
class PersonManager(models.Manager):
def create_person(self, identifier):
person = self.create(identifier = identifier)
return person
しかし、既存の person オブジェクトをどこで確認して取得すればよいかわかりません。
ベストアンサー1
あなたの質問が、取得または作成メソッド(少なくともDjango 1.3以降で利用可能)または更新または作成メソッド (Django 1.7 の新機能)。ユーザー オブジェクトをどのように更新するかによって異なります。
使用例は以下のとおりです。
# In both cases, the call will get a person object with matching
# identifier or create one if none exists; if a person is created,
# it will be created with name equal to the value in `name`.
# In this case, if the Person already exists, its existing name is preserved
person, created = Person.objects.get_or_create(
identifier=identifier, defaults={"name": name}
)
# In this case, if the Person already exists, its name is updated
person, created = Person.objects.update_or_create(
identifier=identifier, defaults={"name": name}
)