Why does Django follow instructions such as:
SELECT (1) AS [a] FROM [my_table]
WHERE ([my_table].[id] = ?
AND NOT ([my_table].[id] = ? )) (1, 1)
This happens when is_valid () is called on a form set created as follows:
MyFormSet = modelformset_factory(Table, fields=['my_field'], extra=0)
my_form_set = MyFormSet(request.POST,
queryset=Table.objects.all())
where Table and MyForm are simple, for example:
class Table(models.Model):
my_field = models.CharField(max_length=10)
class MyForm(forms.ModelForm):
class Meta:
model = Table
Hint: I looked at the call stack and the code responsible for it (in django / forms / models.py) below:
def _perform_unique_checks(self, unique_checks):
import pdb; pdb.set_trace()
bad_fields = set()
form_errors = []
for unique_check in unique_checks:
lookup_kwargs = {}
for field_name in unique_check:
lookup_value = self.cleaned_data[field_name]
if isinstance(self.fields[field_name], ModelChoiceField):
lookup_value = lookup_value.pk
lookup_kwargs[str(field_name)] = lookup_value
qs = self.instance.__class__._default_manager.filter(**lookup_kwargs)
if self.instance.pk is not None:
qs = qs.exclude(pk=self.instance.pk)
Basically, pk is included to verify uniqueness and is excluded. It seems that Django could be smarter and avoid such inefficiencies.
source
share