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'.
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',
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With