如何在Django模型外键上添加条件?

2j4z5cfb  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(102)

我是Django的新手,请你帮助我,我有两个模型,按名称的大陆和国家,在国家形式我想只显示大陆在下拉列表,他们的状态是真的?
模型

from django.db import models
    from smart_selects.db_fields import GroupedForeignKey, ChainedForeignKey
    
    
    class Continent(models.Model):
        name = models.CharField(max_length=255)
        status=models.BooleanField(default=True)
    
        def __str__(self):
            return self.name
    
    class Country(models.Model):
        continent = models.ForeignKey(Continent, null=True, on_delete=models.SET_NULL)
        status=models.BooleanField(default=True)
        name = models.CharField(max_length=255)
        
        def __str__(self):
            return self.name

字符串
形式

class FormContinent(ModelForm):
        class Meta:
            model = Continent
            fields = '__all__'
    
    class FormCountry(ModelForm):
        class Meta:
            model = Country
            fields = '__all__'


观点

def continent(request):
    form = FormContinent()
    if request.method == 'POST':
        form = FormContinent(request.POST)
        form.is_valid()
        form.save()
        return redirect('/continent')
    else:
        context = {'form': form}
        return render(request, 'continent.html', context)

def country(request):
    form = FormCountry()
    if request.method == 'POST':
        form = FormCountry(request.POST)
        form.is_valid()
        form.save()
        return redirect('/country')
    else:
        context = {'form': form}
        return render(request, 'country.html', context)

nkoocmlb

nkoocmlb1#

可以使用**limit_choices_to=…**参数[Django-doc]:

class Country(models.Model):
    continent = models.ForeignKey(
        Continent,
        # ↓ limit choices to Continents with status=True
        limit_choices_to={'status': True},  
        null=True,
        on_delete=models.SET_NULL
    )
    # …

字符串

相关问题