2016-12-12 8 views

答えて

-1

私はthis gistに基づいて、この問題を解決することが一般的に使用することができるように、PKの表記にIDを変更:

# your_app/models.py 

def update_pk(func): 
'''A decorator for pulling a data objects PK value out of a 
    user-defined sequence. This gets around a limitation in 
    django whereby we cannot supply our own sequence names.''' 

    def decorated_function(*args): 
     # Grab a reference to the data object we want to update. 
     data_object = args[0] 

     # Only update the PK if there isnt one yet. 
     if data_object.pk is None: 
      # Construct the new sequence name based on the tables meta data. This might be different depending on your needs 
      sequence_name = 'seq_%s' % data_object._meta.db_table 

      # Query the database for the next sequence value. 
      from django.db import connection 
      cursor = connection.cursor() 
      cursor.execute("SELECT %s.nextval FROM DUAL;" % (sequence_name)) 
      row = cursor.fetchone() 

      # Update the data objects PK with the returned sequence value. 
      data_object.pk = row[0] 

     # Execute the function were decorating. 
     return func(*args) 

    return decorated_function 


# Example model using the decorator to grab the PK. 
class FAQ(models.Model): 
    id = models.IntegerField(primary_key=True) 
    category = models.ForeignKey(FAQCategory) 
    question = models.CharField(maxlength=255) 
    answer = models.TextField() 
    published = models.BooleanField(default=False) 
    list_ordering = models.FloatField(max_digits=6, decimal_places=2, default=9999) 

    def __str__(self): 
     return self.question 

    @update_pk 
    def save(self): 
     # Now actually save the object. 
     super(FAQ, self).save() 

    class Meta: 
     db_table = 'faqs' 
0

私はちょうどこの最後の週に走りました。私のテーブルはMetaにmanaged = falseで定義され、Oracleのシーケンスは主キーの値を提供するために使われます。行が保存された後にキー値を取得するようにDjangoに指示するには、列をAutoFieldとして宣言します。

surrogate_id = models.AutoField(primary_key=True,blank=True) 
+0

フィールドへの入力に使用するシーケンスをどのように宣言しますか? –

+0

Adamは、Django管理テーブルを使用して、Oracleに必要なシーケンスを作成してリンクします。別々にコーディングする必要はありません。私の提案は、既にシーケンス設定がされている管理されていないテーブルでの使用に限定されていました。 – Dashdrum

+0

私の質問は、「管理されていないテーブルを使用すると、新しいシーケンス値をどのように生成して取得するのですか? これまで、挿入トリガーを使用している人がシーケンスから列を更新するのを見てきましたが、私はdjangoの内部でより良い方法を見ていきたいと考えていました。 –

関連する問題