[Solved]-Django – How ModelChoiceField queryset's works?

15👍

Do not use values_list, (or values), ModelChoiceField needs actual model objects.

queryset = sitio_categoria.objects.exclude(categoria='patrimonio')

 

ModelChoiceField will use the primary keys of the objects for validation and their unicode representation for displaying. So you will need to define the conversion to unicode in your model:

class sitio_categoria(models.Model):
    idCategoria = models.AutoField(primary_key=True)
    categoria = models.CharField(max_length=30, null=False, unique=True)

    def __unicode__(self):
        return self.categoria

 

ModelChoiceField documentation

The __unicode__ method of the model will be called to generate string representations of the objects for use in the field’s choices;

Leave a comment