Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are <em>ways</em> to do this </p> <ul> <li>As provided by @obsoleter in <a href="https://stackoverflow.com/questions/10110606/django-admin-many-to-many-intermediary-models-using-through-and-filter-horizont/10203192?noredirect=1#comment18228487_10203192">the comment below</a> : set <code>QuestionTagM2M._meta.auto_created = True</code> and deal w/ syncdb matters.</li> <li><p>Dynamically add <code>date_added</code> field to the M2M model of <code>Question</code> model in models.py</p> <pre><code>class Question(models.Model): # use auto-created M2M model tags = models.ManyToMany(Tag, related_name='questions') # add date_added field to the M2M model models.DateTimeField(auto_now_add=True).contribute_to_class( Question.tags.through, 'date_added') </code></pre> <p>Then you could use it in admin as normal <code>ManyToManyField</code>.<br> In Python shell, use <code>Question.tags.through</code> to refer the M2M model. </p> <p><em>Note</em>, If you don't use <code>South</code>, then <code>syncdb</code> is enough; If you do, <code>South</code> does not like this way and will not freeze <code>date_added</code> field, you need to manually write migration to add/remove the corresponding column. </p></li> <li><p>Customize ModelAdmin:</p> <ol> <li>Don't define <code>fields</code> inside customized ModelAdmin, only define <code>filter_horizontal</code>. This will bypass the field validation mentioned in Irfan's answer.</li> <li>Customize <code>formfield_for_dbfield()</code> or <code>formfield_for_manytomany()</code> to make Django admin to use <code>widgets.FilteredSelectMultiple</code> for the <code>tags</code> field.</li> <li>Customize <code>save_related()</code> method inside your ModelAdmin class, like</li> </ol></li> </ul> <p></p> <pre><code>def save_related(self, request, form, *args, **kwargs): tags = form.cleaned_data.pop('tags', ()) question = form.instance for tag in tags: QuestionTagM2M.objects.create(tag=tag, question=question) super(QuestionAdmin, self).save_related(request, form, *args, **kwargs) </code></pre> <ul> <li>Also, you could patch <code>__set__()</code> of the <code>ReverseManyRelatedObjectsDescriptor</code> field descriptor of ManyToManyField for <code>date_added</code> to save M2M instance w/o raise exception.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload