开发者

Override django form's clean method to change the ModelChoiceField queryset

开发者 https://www.devze.com 2023-03-02 10:48 出处:网络
I have this model: class PetAttribute(models.Model): species = models.ForeignKey(PetSpecies, related_name = \"pets\")

I have this model:

class PetAttribute(models.Model):
    species = models.ForeignKey(PetSpecies, related_name = "pets")
    pet_category = models.ForeignKey(PetCategory, related_name = "pets", blank=True, null=True)
    pet_type = models.ForeignKey(PetType, related_name = "pets", blank=True, null=True)
    additional_fields= models.ManyToManyField( AdditionalField, null= True, blank=True )

Now i want to add an additional option in select (pet_category, pet_type), which is

("0","Other")

in queryset of these. I have tried but form give me an error

Error: Select a valid choice. That 开发者_StackOverflowchoice is not one of the available choices.

here is a one solution of it, but i want to do this by ModelChoiceField

Any suggestion?

Thanks :)


While it is possible, are you sure this is what you want to do? You are telling a field that validates choices to the model objects to accept a non-valid answer.

Creating an "other" PetType and PetCategory object or using empty_label as "other" might make more sense than forcing the ModelChoiceField to accept arbitrary values.

Then to find objects with "other" selected, query for None,

pattrs_w_other_pet_type = PetAttribute.object.filter(pet_type=None)
0

精彩评论

暂无评论...
验证码 换一张
取 消