django admin many-to-many intermediary models using through= and filter_horizontal

后端 未结 3 1865
悲哀的现实
悲哀的现实 2020-12-05 03:08

This is how my models look:

class QuestionTagM2M(models.Model):
    tag = models.ForeignKey(\'Tag\')
    question = models.ForeignKey(\'Question\')
    date_         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 03:58

    From https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models

    When you specify an intermediary model using the through argument to a ManyToManyField, the admin will not display a widget by default. This is because each instance of that intermediary model requires more information than could be displayed in a single widget, and the layout required for multiple widgets will vary depending on the intermediate model.

    However, you can try including the tags field explicitly by using fields = ('tags',) in admin. This will cause this validation exception

    'QuestionAdmin.fields' can't include the ManyToManyField field 'tags' because 'tags' manually specifies a 'through' model.

    This validation is implemented in https://github.com/django/django/blob/master/django/contrib/admin/validation.py#L256

            if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created:
                raise ImproperlyConfigured("'%s.%s' "
                    "can't include the ManyToManyField field '%s' because "
                    "'%s' manually specifies a 'through' model." % (
                        cls.__name__, label, field, field))
    

    I don't think that you can bypass this validation unless you implement your own custom field to be used as ManyToManyField.

提交回复
热议问题