raw_id_fields for modelforms

后端 未结 3 738
挽巷
挽巷 2021-01-01 22:52

I have a modelform which has one field that is a ForeignKey value to a model which as 40,000 rows. The default modelform tries to create a select box with 40,000 options, wh

3条回答
  •  猫巷女王i
    2021-01-01 23:01

    To expand on Voltaire's comment above, the django 1.4 solution is:

    from django.contrib import admin
    admin.autodiscover()
    
    from django.contrib.admin.widgets import ForeignKeyRawIdWidget
    from django import forms
    
    from .models import Post, Photo
    
    class PostForm(forms.ModelForm):
        photo = forms.ModelChoiceField(
            Photo.objects.all(),
            widget=ForeignKeyRawIdWidget(Post._meta.get_field("photo").rel,admin.site)
        )
    

    And the only additional javascript you should need is:

    
    

    The important thing here is that you call autodiscover on the admin, otherwise your RawIdWidget won't have a link. Also the ModelChoiceField requires a queryset, which isn't actually used. ModelChoiceField is preferable to CharField because CharField doesn't validate properly (tries to save the id rather than looking up the Photo instance).

    Update

    Django 2.0 deprecated Field.rel in favor of Field.remote_field.

    That widget= line will now need to be:

    widget=ForeignKeyRawIdWidget(Post._meta.get_field("photo").remote_field, admin.site),
    

提交回复
热议问题