从Djangoadmin中选择另一个foreignkey过滤foreignkey字段?

2024-05-19 09:49:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下一个型号

class Region(models.Model):
    nombre = models.CharField(max_length=25)

class Departamento(models.Model):
    nombre = models.CharField(max_length=25)
    region = models.ForeignKey(Region)

class Municipio(models.Model):
    nombre = models.CharField(max_length=35)
    departamento = models.ForeignKey(Departamento)

我需要根据所选地区筛选部门中的选项,并根据所选部门筛选市政部门中的选项。在

有可能吗??在

谢谢大家!在


Tags: modelmodels选项lengthregionmaxclass部门
1条回答
网友
1楼 · 发布于 2024-05-19 09:49:04

假设您是在一系列选择框中讨论此操作:

创建两个视图,其中一个视图返回包含给定区域的departmentos的响应。另一个也一样,但在一个部门的市政当局

# views.py
from django.core import serializers

def departamentos_por_region(request, region_id):
    region = get_object_or_404(Region, id=region_id)
    departamentos = Departamento.objects.filter(region=region)
    return render_to_reponse("format_as_option_list.html",
                             {'departamentos': departamentos})

def municipios_por_departamento(request, departamento_id):
    # basically the same as above

我假设您在初始页面视图中填充区域选择框,因此不需要特殊视图。在

模板应将departmentos格式化为html选项列表。在

假设初始页面视图中的HTML类似于:

^{pr2}$

您可以使用一些javascript(在jQuery中):

// this isn't tested code and likely contains an error or two
$('#regions').change(function(){

    // Region has changed, so reset Departamentos and Municipios
    $('#departamentos').html("")
    $('#municipios').html("")

    // now update the departamentos
    $.get('/ajax/departamentos_por_region/' +  $('#regions').val(),
          function(data) {
              ('#departamentos').html(data)    
          };     
    );
});

对市政当局和部门也一样。在

您可能还希望在字段没有可用选项时禁用这些字段,并处理没有departamentos或municipios返回的情况。在

相关问题 更多 >

    热门问题