如何获取相关模型的所有记录并在Django中显示动态数据

时间:2018-12-11 11:16:25

标签: python django

我是django的新手。我想从相关模型中检索所有记录,并在模板中显示动态数据。我也尝试使用原始sql,但无法显示动态数据模板。

models.py:

 class NewRegistration(models.Model):
    houseowner_name_en = models.CharField(max_length=30)
    ward_no = models.ForeignKey(system_settings.models.Wardno)
    contactno = models.CharField(max_length=30)
    construction_type = models.ForeignKey(system_settings.models.ConstructionType)
    taxpayer_id = models.CharField(max_length=30, blank=True, null=True)
    cen = models.IntegerField()
    is_forwarded = models.BooleanField(default=False)


class Application(models.Model):
    registration_date = models.CharField(max_length=15)
    building_use = models.ForeignKey(to=system_settings.models.BuildingUse)
    building_category = models.CharField(max_length=30)
    building_structure_category = models.ForeignKey(to=system_settings.models.BuildingStructureCategory)
    building_storey = models.IntegerField(blank=True, null=True, default=0)

    reg = models.ForeignKey(NewRegistration)


class Landowner(models.Model):
    landowner_type = models.CharField(max_length=30)
    lo_salutation = models.CharField(max_length=30)
    lo_name_np = models.CharField(max_length=30)
    lo_citizenship_issue_date = models.CharField(max_length=30)
    reg = models.ForeignKey(NewRegistration)        

views.py:

def export(request):
    all_objects = NewRegistrationModel.objects.all()
     # houseowner= all_objects.houseownerinfo_set.all()
    app_all=Application.objects.all()
    landinfo=Landinfo.objects.all()
    return render(request, 'exports.html', {'all_objects': all_objects})

2 个答案:

答案 0 :(得分:0)

您可以像这样在您的views.py文件中使用generic.ListView:

class Export(generic.ListView):
    model = NewRegistration
    template_name = "your_template_name.html"  

    def get_queryset(self):
        return NewRegistration.objects.all()

    def get_context_data(self, **kwargs):
       context = super(Export, self).get_context_data(**kwargs)
       context['app_all'] = Application.objects.all()
       context['landinfo'] = Landingo.objects.all()
       return context

您可以访问模板中的数据,例如{{app_all}}或{{landinfo}}。

答案 1 :(得分:0)

我是这样做的。

views.py

def export(request):
    all_objects = NewRegistration.objects.all()
    return render(request, 'exports.html', {'all_objects': all_objects})

exports.html

# in template when displaying
{% for registration in all_objects %}
    {{ registration.fiscalyear }}
    {% for owner in registration.landowner_set.all %}
        {{owner.landowner_type}}
        {{owner.lo_wardno}}
    {% endfor %}
{% endfor %}