django-parler-管理员M2M字段的M2M关系问题(循环依赖?)

时间:2018-09-20 15:02:27

标签: python django circular-dependency m2m

我们在使用M2M关系时面临一个问题-似乎我们有一个循环依赖问题?

我们需要与Admin中公开的TranslatableModel字段(内部是M2M)建立M2M关系(我们有一个利用M2M字段的多选小部件)。

许多研究仅揭示了此特定的调试信息(感谢@egasimus):

models.py

# Here's a pretty basic model with a translatable M2M field.

class ContentItem(TranslatableModel):

    translations = TranslatedFields(
        title = models.CharField(max_length=200),

        content = models.TextField(blank=True),

        primary_media = models.ForeignKey(
            'media.MediaAsset', related_name='cards_where_primary',
            blank=True, null=True)

        extra_media = models.ManyToManyField(
            'media.MediaAsset', related_name='cards_where_extra',
            blank=True, null=True))

    author = models.ForeignKey(settings.AUTH_USER_MODEL)

    created = models.DateTimeField(auto_now_add=True)

    modified = models.DateTimeField(auto_now=True)

admin.py

class ContentItemAdmin(TranslatableAdmin):
    fields = ('title', 'content', 'primary_media', 'extra_media',
              'author', 'created', 'modified')

# The above code results in the following error: 
#     FieldError at /admin/cms/contentitem/1/
#     Unknown field(s) (extra_media) specified for ContentItem. Check fields/fieldsets/exclude attributes of class CardAdmin.


class ContentItemAdmin(TranslatableAdmin): pass

# And, if I don't explicitly define fields, the `extra_media` field doesn't show up at all.

# This is confirmed if I run `manage.py shell` and I retrieve a ContentItem instance:
# it simply does not have an `extra_media` attribute. However, if I do manually retrieve
# a translation instance, the `extra_media` M2M field is there - it just doesn't end up
# getting added to the shared object.

models.py

# Adding a call to `get_m2m_with_model()`, though, makes any translated M2M fields
# appear on the shared object, and in the admin.

class TranslatedFieldsModel(models.Model):

    def _get_field_values(self):
        return [getattr(self, field.get_attname()) for field, _
                in self._meta.get_fields_with_model()
                    + tuple(self._meta.get_m2m_with_model())]

    @classmethod
    def get_translated_fields(cls):
        return [f.name for f, _
                in cls._meta.get_fields_with_model()
                    + tuple(cls._meta.get_m2m_with_model())
                if f.name not in ('language_code', 'master', 'id')]


# However, when I try to save a new ContentItem via the admin,
# I get the aforementioned error:
#
#     "<ContentItemTranslation: #None, bg, master: #None>" needs to have a value for field
#         "contentitemtranslation" before this many-to-many relationship can be used.
#
# I assume that this has to do with the order in which the shared model, the translation model,
# and the M2M intermediate model interact, and the order in which they are saved.

有人遇到这样的问题吗?关于如何解决这个问题的任何指示?

感谢您提供的任何帮助。

0 个答案:

没有答案