Search code examples
pythondjango-modelsforeign-key-relationshiplimit-choices-to

How to define django foreign key limit_choices_to constraint which has reference to it's own model?


Here are the models. I need to avoid the reference of Filter objects in the FilterValue model which are being already referenced in the FilterValue model.

    class Filter(models.Model):
        name = models.CharField('Name', max_length=255)

    class FilterValue(models.Model):
        name = models.CharField('Name', max_length=255)
        filter = models.ForeignKey(Filter, limit_choices_to=Q(***?***))

I'm looking for what could be the possible in place of ?.


Solution

  • As I understood from the OP's comment, the idea is to forbid adding duplicate entries.

    But there is a more secure way of doing that:

    class FilterValue(models.Model):
        name = models.CharField('Name', max_length=255)
        filter = models.ForeignKey(Filter)
    
        class Meta:
            unique_together = (("name", "filter"),)
    

    The original solution will just display a list of Filters in the Admin, of in a Form, but will not actually forbid to add a duplicate programatically.