が発生します。今すぐDjangoのORM Model.objects.raw()クエリは、私は、次の(簡体字)のモデル持っている無限の再帰エラー
class Common(models.Model):
id = models.BigAutoField(primary_key=True, editable=False)
date_created = models.DateTimeField()
class Meta:
abstract = True
def __init__(self, *args, **kwargs):
super(Common, self).__init__(*args, **kwargs)
self._initial_data = {}
self.track_fields(
'date_created',
)
def track_fields(self, *args):
for field_name in args:
self._initial_data[field_name] = getattr(self, field_name)
class Directory(Common):
directory_path = models.TextField()
parent_directory = models.ForeignKey('self')
class File(Common):
removed = models.BooleanField()
parent_directory = models.ForeignKey(Directory)
を、私は簡略化した例(このようないくつかのオブジェクトを照会しようとしています、SQLは)最初の場所で使用された理由に全く注意を払っていない:
sql_select_dirs_of_deleted_files = '''
select d.id, directory_path
from directory d
left join file f on f.parent_directory_id = d.id
where f.removed = true and f.id in %s
group by d.id, directory_path
order by directory_path asc
'''
dirs_of_deleted_files = Directory.objects.raw(sql_select_dirs_of_deleted_files, [tuple(file_ids)])
parent_of_top_dir = dirs_of_deleted_files[0].parent_directory
がdirs_of_deleted_files[0]
へのアクセスライン上で無限再帰エラーが発生し
self._initial_data[field_name] = getattr(self, field_name)
共通モデルの
私は継承とgetattrの再帰問題を認識していますが、models.Model.__getattribute__(self, field_name)
を使用しても違いはありません。しかし、何の代わりに作業を行うことである。
dirs_of_deleted_files = Directory.objects \
.filter(files__in=file_ids, files__removed=True) \
.distinct('id', 'directory_path') \
.order_by('directory_path')
、dirs_of_deleted_files[0]
にアクセスしても、無限再帰エラーが発生することはありません。
共通モデルは他のいくつかのモデルに継承されており、別の場所で多くのインスタンスを明示的にインスタンス化し、このDirectory.objects.raw()
メソッドを使用するまではgetattr()
は決して問題を引き起こしませんでした。何故なの?私はDjangoのバグだと思うだろうが、私は自分の判断を保つだろう。
あなたの例に不可欠なクラスMetaを追加しました。これとは対照的に、この例を簡素化し、一貫性を維持して問題を再現できるようにすることもできます。どちらもStackoverflowでお勧めします。幸いにもあなたの質問は十分に面白く、修正することができます。 – hynekcer
非常に感謝しています!あなたは正しいです、その例は、より簡単でより完全なものになります。まもなく修正されます。 – hannu40k