2016-07-08 8 views
0

私のアプリケーションでは、所有者は所有者が1人または複数の人または会社になることができますが、時間。人と会社は2つの異なるモデルです。所有権日付、廃棄日などの重要な情報を関連付けるために、所有権をモデルに使用したいと思います。所有者が個人または会社になることができるアイテムと所有者との関係を作成する方法

どのようにモデルをDjangoでモデル化しますか?私はPostgres 9.1を使用しています

答えて

0

「Generics」をサポートする組み込みのdjango.contrib.contenttypeアプリ、つまりいくつかのモデルの1つを指し示すかもしれない外部キーを使用しています。それはインラインフォームのようなフォーム要素を提供するので非常に強力です。ここで

は、ジェネリック医薬品についてのいくつかのリソースです:

https://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/#generic-relations-in-admin http://screamingatmyscreen.com/2012/6/django-and-generic-relations/

0

私は自分のプロジェクトでdjango-polymorphicを使用して多くの成功を持っていた、それは非常に使いやすいです。

は、バージョン0.9.2の時点で、あなたは(ドキュメントから直接取られ)そうのような多型のモデルを実装することができます

from polymorphic.models import PolymorphicModel 

class Project(PolymorphicModel): 
    topic = models.CharField(max_length=30) 

class ArtProject(Project): 
    artist = models.CharField(max_length=30) 

class ResearchProject(Project): 
    supervisor = models.CharField(max_length=30) 

作成モデル:

>>> Project.objects.create(topic="Department Party") 
>>> ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner") 
>>> ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter") 

取得多形クエリ結果:

>>> Project.objects.all() 
[ <Project:   id 1, topic "Department Party">, 
    <ArtProject:  id 2, topic "Painting with Tim", artist "T. Turner">, 
    <ResearchProject: id 3, topic "Swallow Aerodynamics", supervisor "Dr. Winter"> ] 

あなたのケースでは、次のようなモデルを設定することができます:

class Owner(PolymorphicModel): 
    date_of_ownership = ... 
    date_of_disposal = ... 

class Person(Owner): 
    pass 

class Company(Owner): 
    pass 

class Item(models.Model): 
    owner = ForeignKey(Owner) 
関連する問題