如何定义m2m_reverse_name_cache?

时间:2017-08-23 12:50:07

标签: django django-models

我需要为继承相同模型的两个版本元素之间的OneToOne关系建立一个自定义关系表(无论模型是什么)。为此,这里是模型和关系模型。

class Ensemble(models.Model):
    name = models.CharField("Nom", max_length=50)
    version = models.CharField("Version", max_length=10, blank=True, default=None, null=True)
    parent_version = models.OneToOneField("self",verbose_name="Version du parent",
                                       default=None, blank=True, null=True, related_name="children_version", unique=False)
    version_up = models.ManyToManyField('Ensemble', through='Version_up', symmetrical=False, blank=True, related_name='version_up_set')

class Version_up(models.Model):
    child_element = models.ForeignKey(ContentType ,on_delete=models.CASCADE, blank=True, null=True, related_name="child_element")
    parent_element = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True, related_name="parent_element")
    description = models.TextField(max_length=1000, verbose_name="Commentaires", default=None, blank=True, null=True)
    child_id = models.PositiveIntegerField()
    parent_id = models.PositiveIntegerField()
    child_content = GenericForeignKey('child_element' ,'child_id')
    parent_content = GenericForeignKey('parent_element', 'parent_id')

但是,当我尝试访问Ensemble模型的管理器时,出现此错误:{AttributeError}'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'

我已阅读AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'这篇文章,但它并不适用于我的问题,因为我需要存储有关该关系的额外数据。在此先感谢您的帮助。

以下是触发错误的视图:

def validate_form_ensemble(elem_id, request):
    """
    :param elem_id:
    :param request:
    :return:
    """
    instance = Ensemble.objects.get(id=elem_id)
    form = EnsembleForm(QueryDict(request.POST.get('form')),instance=instance)
    if form.errors:
        form = EnsembleForm(custom_decode(QueryDict(request.POST.get('form')), Ensemble))
    if form.is_valid():
        form.save()
        response = 'Ensemble enregistré'
    else:
        response = form.errors
    return response

这是完整的追溯。

Internal Server Error: /Syc/update_elem/EN/31
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Program Files (x86)\Python\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "C:\Program Files (x86)\Python\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files (x86)\Python\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:/Users/USER/Documents/Projet/Sycoma\Syc\views\views_utils.py", line 676, in _wrapped_view
    return view(request,*args,**kwargs)
  File "C:/Users/USER/Documents/Projet/Sycoma\Syc\views\ajax_views.py", line 182, in update_elem
    response = validate_form_ensemble(elem_id, request)
  File "C:/Users/USER/Documents/Projet/Sycoma\Syc\views\views_utils.py", line 564, in validate_form_ensemble
    form = EnsembleForm(QueryDict(request.POST.get('form')),instance=instance)
  File "C:\Program Files (x86)\Python\lib\site-packages\django\forms\models.py", line 287, in __init__
    object_data = model_to_dict(instance, opts.fields, opts.exclude)
  File "C:\Program Files (x86)\Python\lib\site-packages\django\forms\models.py", line 96, in model_to_dict
    data[f.name] = f.value_from_object(instance)
  File "C:\Program Files (x86)\Python\lib\site-packages\django\db\models\fields\related.py", line 1683, in value_from_object
    return getattr(obj, self.attname).all()
  File "C:\Program Files (x86)\Python\lib\site-packages\django\db\models\fields\related_descriptors.py", line 513, in __get__
    return self.related_manager_cls(instance)
  File "C:\Program Files (x86)\Python\lib\site-packages\django\db\models\fields\related_descriptors.py", line 803, in __init__
    self.target_field_name = rel.field.m2m_reverse_field_name()
  File "C:\Program Files (x86)\Python\lib\site-packages\django\utils\functional.py", line 15, in _curried
    return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs))
  File "C:\Program Files (x86)\Python\lib\site-packages\django\db\models\fields\related.py", line 1617, in _get_m2m_reverse_attr
    return getattr(self, cache_attr)

1 个答案:

答案 0 :(得分:0)

我还没有找到解决此问题的方法,但这是一种解决方法:

    instance=elem_model.objects.get(pk=elem_id)
    try:
        form = ModelForm(data, instance=instance)
    except AttributeError:
        form = ModelForm(data)
        form.instance = instance

对于其他情况而不是使用我的模型管理器,我只使用关系表的实例。