比较数据库中的两个字段数据

时间:2013-08-06 10:01:56

标签: python django django-models django-forms django-templates

models.py

class ReportType(models.Model):
    report = models.ForeignKey(Report)
    title = models.CharField('Incident Type', max_length=200)

class Report(models.Model):
    user = models.ForeignKey(User, null=False)
    app_uuid = models.CharField('Unique App Id', max_length=100)

class Types(models.Model):
    user = models.ForeignKey(User, null=True)
    title = models.CharField('Incident Type', max_length=200)
    is_active = models.BooleanField('Is Active', default=True)

在Types表中,我在title字段中保存了一些默认数据。用户输入的数据保存在ReportType表中。

我想比较Types模型和ReportType模型中title属性中的数据。经过比较,如果在ModelType模型中不存在ReportType模型中的title字段数据,我需要在模板中显示它。我需要显示非ReportType模型中存在的匹配值。

template.html

{% for type in report_type %} 
 {{type.title}}{% endfor %}

我尝试过这个查询

 report_type = Report.objects.filter(reporttype__title=F('types__title')) 

我收到此错误"Cannot resolve keyword 'types' into field",这是因为Types表与Report表没有关系。需要帮助。

2 个答案:

答案 0 :(得分:0)

您似乎至少需要2个查询:

# get all types as a list
all_types = Types.objects.values_list('title', flat=True)

# you need to show the mismatch, then use exclude()
report_type = ReportType.objects.exclude(title__in=all_types)

希望它有所帮助。

答案 1 :(得分:0)

您可以过滤ReportType对象并从结果查询集中获取报告,如下所示:

ReportType.objects.values_list('report').filter(title__in=Types.objects.values_list('title', flat=True).distinct())
相关问题