Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

admin inline ManyToMany autocomplete_fields

I want to add search for the AcademicGroupInline with using its vk_chat relation

# models.py

class AcademicGroup(models.Model):
    students = models.ManyToManyField(
        'user.Student',
    )
    vk_chat = models.OneToOneField(
        'Chat',
    )


class Chat(models.Model):
    owner_id = models.BigIntegerField()
    name = models.CharField()


# admin.py

class AcademicGroupInline(admin.TabularInline):
    model = AcademicGroup.students.through
    autocomplete_fields = (
        'vk_chat',
    )


@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
    inlines = [AcademicGroupInline]

But I've got an error in result:

<class 'user.admin.AcademicGroupInline'>: (admin.E037) The value of 'autocomplete_fields[0]' refers to 'vk_chat', which is not an attribute of 'course.AcademicGroup_students'.
like image 933
user13154885 Avatar asked Oct 20 '25 14:10

user13154885


1 Answers

First, you should register AcademicGroup model, as you did with Student, and add in search_fields attribute which should have vk_chat as value.

@admin.register(AcademicGroup )
class AcademicGroupAdmin(admin.ModelAdmin):
      ....
      search_fields = ['vk_chat']

Second, in your AcademicGroup model, you should add in your M2M field this parameter related_name='academicgroups' (you can name it as you want).

Third, in your AcademicGroupInline class, you should put Student.AcademicGroup.through in model field instead of AcademicGroup.students.through because i guess you want to list Acadamicgroups associated to student not the inverse.

Finally, in your autocomplete_fields you can put only attributes of the model created by AcademicGroup.students.through, so i suggest you to print those attributes using print(model._meta.fields) inside your AcademicGroupInline class (i think you will get id, student and academicgroup). So, your autocomplete_fields should have academicgroup as a value.

class AcademicGroupInline(admin.TabularInline):
    model = Student.academicgroups.through
    autocomplete_fields = (
        'academicgroup',
    )
like image 139
achraf bouzekri Avatar answered Oct 22 '25 04:10

achraf bouzekri