9

これはまったく意味がないので、私は本当に途方に暮れています。オブジェクトの保存/作成を呼び出しましたが、管理サイトに表示されません。SQLite Viewer プログラムを使用して SQLite データベースをチェックしたところ、アイテムが保存されていないことが再び示されました。

Dataオブジェクトを保存するコードは次のとおりです。

        data = Data(represents=field, for_entry=entry, value="This can be anything")
        # field is a DataField db object and entry is a Entry db object (see model below and paragraph)
        print("B4", data) #<---- Shows that Data has not been assigned an ID/pk
        data.save()
        print("8ER: ", data) #<--- Shows that Data has been assigned an ID/pk

私のコメントからわかるように、save呼び出し後に Data オブジェクトに ID が割り当てられていることがわかります。これは、それが機能したことを意味すると思います。どこにもエラーはスローされません。field、およびentryすべて両方です。正しい ID を持っていて、 で取得され[table name].objects.get(id=...)、保存/編集でき、保存内容が変更されるため、それぞれ問題ないようです。

奇妙なことに、これが機能する直前に呼び出される関数内の正確なコードです。

これは私のmodel.pyです(短くするためにいくつかの機能を取り出しました):

class Entry(models.Model):
    parent = models.ForeignKey('Entry', blank = True, null = True, default=None) #  The entry this subs. Is left blank for top level entries.
    id_number = models.CharField(max_length=20)
    visible = models.BooleanField()
    data_field = models.ForeignKey('DataField', default=1)  # The field that this entire entry falls under. REDUNDANT BUT NECISSARY

    def __str__(self):
        return str(self.id)+ "-" + str(self.id_number) 

class DataField(models.Model):
    parent = models.ForeignKey('DataField', related_name='parent field', null=True, blank=True, default=1)
    order = models.IntegerField()
    multiple_entries = models.BooleanField(default=True)
    DATA_TYPES = (('t', 'Text'), ('d', 'Date'), ('l', 'List'), ('o', 'Option'), ('b', 'Boolean'), ('f', 'Foreign Key'), ('r', 'Root'), ('bb', 'Branch'), ('i', 'Image'), ('ff', 'File'), ('h', 'Holder'), ('bt', 'Big Text'))  # A number means it is a foreign key. Should go off title.
    foreign_source = models.ForeignKey('DataField', null=True, blank=True) #  Points to DATA FIELD WHO'S MATCHING DATA WILL MAKE UP THE OPTIONS
    data_type = models.CharField(max_length=2, choices=DATA_TYPES, default='t', null=True, blank=True)
    title = models.CharField(max_length=100, null=True, blank=True)
    visibility = models.BooleanField(default=False)

    def __str__(self):
        return str(self.id) + "-" + str(self.title)

    def __eq__(self, other):
        if not isinstance(other, DataField):
            return False
        if self.data_type == 'h':
            return self.title == other.title
        return self.id == other.id


class Data(models.Model):
    represents = models.ForeignKey('DataField')
    for_entry = models.ForeignKey('Entry', null=True)
    value = models.CharField(max_length=1000000)

    def __str__(self):
        return self.represents.title + "-" + str(self.for_entry.id) + "-" + str(self.value) + "-" + str(self.id)

明らかな何かが欠けている可能性があります。または、それを修正するために提供できるよりも多くの情報が必要な場合があります。十分な情報がない場合は、コメントして詳細情報を要求するか、発生している可能性のある問題をリストしてください。

4

4 に答える 4

3

単体テストを実行して同様の問題が発生し、保存方法が機能していないように見えるエラーが発生しました->次のようになりました

p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, value) 
myfunc()  # Code that changed the same object p is referencing
self.assertEqual(p.my_attr, new_value)

参照されているオブジェクトを新しい値に変更し、オブジェクトに対して .save() を実行しても、上記は失敗しました。

この問題を解決するには、p を MyModel オブジェクトに再割り当てする必要がありました。単体テストで修正したコードは次のようになりました。

p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, value) 
myfunc()  # Code that changed the same object p is referencing
p = MyModel.objects.get(pk=myparam)
self.assertEqual(p.my_attr, new_value)

メモリ内の古い場所を指している変数に問題があるようですが、5 か月前にプログラミングを始めたばかりなので、少し頭がいっぱいです :) 誰かがこれが起こっている理由を説明できる場合は、フィードバックをいただければ幸いです。私はまだ困惑しているので。

save メソッドが実行されているとは思えない場合は、save メソッドを上書きして print ステートメントを追加することで、サニティ チェックを実行できます。次のようになります。

class MyModel(models.Model):
    attr = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        super(MyModel, self).save(*args, **kwargs)
        print('Did this attribute update? (attr):', self.attr)
        print('Save method executed!')

編集:メモリ位置理論に沿って、この簡単な例を作成しました:

In [3]: a = 1
In [4]: b = a
In [5]: hex(id(a))
Out[5]: '0x100240280'
In [6]: hex(id(b))
Out[6]: '0x100240280'
In [7]: a = 2
In [8]: b
Out[8]: 1
In [9]: hex(id(a))
Out[9]: '0x1002402a0'
In [10]: hex(id(b))
Out[10]: '0x100240280'

まだ誰かの考えを聞きたいです。

于 2016-01-28T05:48:42.363 に答える
0

django refresh_from_db()更新する必要があるオブジェクトで関数を使用します。

于 2019-10-14T06:42:25.567 に答える