1

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 ?.

Babu
  • 2,548
  • 3
  • 30
  • 47
  • So you want when setting a Filter to the FilterValue and saving the model, not to see it in the list anymore? What is the purpose of such solution? – Tisho Jun 14 '12 at 11:46
  • not to add duplicate entries. – Babu Jun 14 '12 at 14:59
  • Maybe I cannot understand it right, but I think this is not the right way of doing it... – Tisho Jun 14 '12 at 15:32

3 Answers3

1

You can't do it in that way, but you can do it as part of a form. Specifically, during the __init__ method of a form, you can alter the queryset of a related field.

I wrote about how to do this in the admin at Filtering querysets in django.contrib.admin forms

Matthew Schinckel
  • 35,041
  • 6
  • 86
  • 121
1

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.

Tisho
  • 8,320
  • 6
  • 44
  • 52
0

I did it in another way by making FilterValueAdmin edit-only in admin and adding the same as inline in FilterAdmin model.

class FilterValueInline(admin.StackedInline):
   formset = FilterValueInlineFormset
   model = FilterValue
   max_num = 1
   can_delete = False


class FilterAdmin(admin.ModelAdmin):
   list_display = ('id', 'name')
   inlines = [FilterValueInline]


class FilterValueAdmin(admin.ModelAdmin):
   """Filter value has to be added via the filter table"""
   def has_add_permission(self, request):
       return False
   def has_delete_permission(self, request, obj=None):
       return False
   actions = None
   list_display = ('id', 'name', 'filter')
Babu
  • 2,548
  • 3
  • 30
  • 47