Django 4.2. How can djanjo-admin make a pre-selection of the values of a model field that is a ForeignKey, if it is specified in autocomplete_fields?

The following code works as required, if you comment out the line autocomplete_fields = ('code',). Then there are objects in the drop-down list that have only one of the required types. But if you remove the comment, then all objects are already offered in the autocomplete field, without pre-select.

models.py

class SignalsGuide(models.Model):
    TYPE_CHOICES = [
        ("signals", "Signal"),
        ("pdata", "Passport value"),
        ("constants", "Constant"),
        ("diag", "Diag value"),
    ]
    
    id = models.BigAutoField(primary_key=True)
    code = models.CharField(max_length=100, verbose_name='Code')
    type = models.CharField(
        max_length=30, choices=TYPE_CHOICES, default="signals",
        verbose_name='Signal type')

def __str__(self) -> str:
    return self.code


class Params(models.Model):
    id = models.BigAutoField(primary_key=True)
    code = models.ForeignKey(
        'SignalsGuide', models.DO_NOTHING, db_column='code',
        verbose_name='Code')
    value = models.CharField(
        max_length=400, blank=True, null=True, verbose_name='Value')

    def __str__(self) -> str:
        return f"{self.code.code}: {self.value}"

admin.py

class ParamsAdmin(admin.ModelAdmin):
    _param_types = ("pdata", "constants")
                   
    list_display = ('id', 'code', 'value')
    search_fields = ('id', 'code__code', 'value')
    autocomplete_fields = ('code',)
    list_select_related = ('code',)
    
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "code":
            kwargs["queryset"] = SignalsGuide.objects.filter(type__in=self._param_types)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
0

There are 0 best solutions below