Ticket #11707: limit_ForeignKey.patch

File limit_ForeignKey.patch, 3.0 KB (added by Chris.Wesseling@…, 15 years ago)
  • django/db/models/fields/related.py

     
    749749        defaults = {
    750750            'form_class': forms.ModelChoiceField,
    751751            'queryset': self.rel.to._default_manager.complex_filter(
    752                                                     self.rel.limit_choices_to),
     752                                                    self.rel.limit_choices_to).distinct(),
    753753            'to_field_name': self.rel.field_name,
    754754        }
    755755        defaults.update(kwargs)
  • tests/regressiontests/model_fields/tests.py

     
    11import datetime
    22import unittest
     3import re
    34
    45import django.test
    56from django import forms
    67from django.db import models
    78from django.core.exceptions import ValidationError
    89
    9 from models import Foo, Bar, Whiz, BigD, BigS, Image
     10from models import Foo, Bar, Baz, Whiz, BigD, BigS, Image
    1011
    1112try:
    1213    from decimal import Decimal
     
    7273        # This should not crash. That counts as a win for our purposes.
    7374        Foo.objects.filter(d__gte=100000000000)
    7475
     76class BazForm(forms.ModelForm):
     77    class Meta:
     78        model = Baz
     79
    7580class ForeignKeyTests(django.test.TestCase):
    7681    def test_callable_default(self):
    7782        """Test the use of a lazy callable for ForeignKey.default"""
     
    7984        b = Bar.objects.create(b="bcd")
    8085        self.assertEqual(b.a, a)
    8186
     87    def test_distinct_choice_limit(self):
     88        """Doesn't make sense to offer the same ForeignKey multiple times in a form"""
     89        a = Foo.objects.create(a='a', d=Decimal("-1"))
     90        b = Foo.objects.create(a='b', d=Decimal("1"))
     91        bar_a = Bar.objects.create(b='ah', a=a)
     92        bar_b = Bar.objects.create(b='aha', a=a)
     93        bar_b = Bar.objects.create(b='bla', a=b)
     94        form = BazForm()
     95        fk_field = str(form['foo'])
     96        self.assertEqual(len(re.findall(r'value="2"', fk_field)), 0)
     97        self.assertEqual(len(re.findall(r'value="1"', fk_field)), 1)
     98
    8299class DateTimeFieldTests(unittest.TestCase):
    83100    def test_datetimefield_to_python_usecs(self):
    84101        """DateTimeField.to_python should support usecs"""
  • tests/regressiontests/model_fields/models.py

     
    2929    b = models.CharField(max_length=10)
    3030    a = models.ForeignKey(Foo, default=get_foo)
    3131
     32class Baz(models.Model):
     33    a = models.CharField(max_length=5)
     34    #Only Foos related to Bars starting with 'a'
     35    foo = models.ForeignKey(Foo, limit_choices_to=models.Q(bar__b__startswith='a'))
     36
    3237class Whiz(models.Model):
    3338    CHOICES = (
    3439        ('Group 1', (
Back to Top