如何允许用户动态过滤模型并仅导出某些字段?

时间:2017-08-23 15:31:19

标签: django django-models

我被要求设计一种方式让人们根据他们输入的标准搜索多个模型,并允许他们导出他们选择的任意数量的字段。

实施例: 用户输入“教师”作为职务名称和“Google”作为工作地点位置,但要输出“员工ID”,“名字”,“姓氏”,“出生日期”

我确信这是可能的,但我完全不知道从哪里开始。

我的模型(供参考)在这里:

import datetime
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils import timezone


class Classification(models.Model):
    name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Classification Name')

    def __str__(self):
        return '{}'.format(self.name)

    class Meta:
        db_table = 'Classification'
        verbose_name = 'Classification'
        verbose_name_plural = 'Classifications'


class Location(models.Model):
    name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
    aeries_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='Aeries ID')
    county_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='County ID')

    def __str__(self):
        return '{}'.format(self.name)

    class Meta:
        db_table = 'Location'
        verbose_name = 'Location'
        verbose_name_plural = 'Locations'
        ordering = ['name']


class Person(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True)
    current_identity = models.ForeignKey('PersonIdentity', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Current Identity', related_name='current_identity')
    employee_id = models.CharField(max_length=255, null=False, blank=False, verbose_name='Employee ID')
    birthdate = models.DateField(blank=True, null=True, verbose_name='Birthdate')
    original_hire_date = models.DateField(blank=True, null=True, verbose_name='Original Hire Date')

    def __str__(self):
        if self.current_identity is not None:
            return '{}'.format(str(self.current_identity))
        else:
            return "{}".format(self.employee_id)

    @property
    def current_age(self):
        from dateutil.relativedelta import relativedelta
        difference_in_years = relativedelta(timezone.now().date(), self.birthdate).years
        return difference_in_years

    def primary_assignment(self):
        return self.jobassignment_set.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).order_by('priority')[0]

    @property
    def display_name(self):
        if self.current_identity:
            return '{0.first_name} {0.last_name} ({1.employee_id})'.format(self.current_identity, self)
        else:
            return 'Employee ID {0.employee_id}'.format(self)

    @property
    def is_certificated(self):
        assignments = JobAssignment.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).filter(
            person=self,
            classification__name__icontains="Certificated"
        )
        return assignments.count() >= 1

    class Meta:
        db_table = 'Person'
        verbose_name = 'Person'
        verbose_name_plural = 'People'


class PersonIdentity(models.Model):
    person = models.ForeignKey(Person, verbose_name='Person', on_delete=models.CASCADE)
    first_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='First Name')
    middle_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Middle Name')
    last_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Last Name')
    start_date = models.DateField(blank=False, null=False, default=datetime.date.today, verbose_name='Start Date')
    end_date = models.DateField(blank=True, null=True, verbose_name='End Date')

    def __str__(self):
        first_name = '' if self.first_name is None else self.first_name
        last_name = '' if self.last_name is None else self.last_name
        if self.middle_name is not None and self.middle_name != '':
            return "{} {}. {} ({})".format(first_name, self.middle_name[0], last_name, self.person.employee_id)
        else:
            return "{} {} ({})".format(first_name, last_name, self.person.employee_id)

    def save(self, *args, **kwargs):
        change_identity = False
        if not self.id:
            change_identity = True
        super().save(*args, **kwargs)
        if change_identity:
            self.person.current_identity = self
            self.person.save()

    class Meta:
        db_table = 'PersonIdentity'
        verbose_name = 'Person Identity'
        verbose_name_plural = 'Person Identities'
        ordering = ['end_date', 'last_name', 'first_name']


class Contact(models.Model):
    person = models.OneToOneField(Person, on_delete=models.CASCADE, verbose_name='Person')
    email_address = models.EmailField(blank=True, null=True, verbose_name='Primary Email')
    phone_number = models.CharField(max_length=15, blank=True, null=True, verbose_name='Phone Number')
    phone_extension = models.CharField(max_length=255, blank=True, null=True, verbose_name='Phone Extension')
    address1 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 1')
    address2 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 2')
    city = models.CharField(max_length=255, blank=True, null=True, verbose_name='City')
    state = models.CharField(max_length=2, default='CA', blank=True, null=True, verbose_name='State')
    postal = models.CharField(max_length=5, blank=True, null=True, verbose_name='Postal Code')

    def __str__(self):
        return '{}'.format(self.person.current_identity)

    class Meta:
        db_table = 'Contact'
        verbose_name = 'Contact'
        verbose_name_plural = 'Contacts'


class Department(models.Model):
    department_id = models.CharField(max_length=5, blank=False, null=False, verbose_name='Department ID')
    description = models.CharField(max_length=255, blank=False, null=False, verbose_name='Department Description')

    def __str__(self):
        return '{}'.format(self.description)

    class Meta:
        db_table = 'Department'
        verbose_name = 'Department'
        verbose_name_plural = 'Departments'


class Job(models.Model):
    name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
    code = models.CharField(max_length=255, blank=False, null=False, verbose_name='Code')

    def __str__(self):
        return '{}'.format(self.name)

    class Meta:
        db_table = 'Job'
        verbose_name = 'Job'
        verbose_name_plural = 'Jobs'


class JobPosition(models.Model):
    job = models.ForeignKey(Job, blank=True, null=True, verbose_name='Job')
    reports_to = models.ForeignKey('JobPosition', blank=True, null=True, verbose_name='Reports To')
    name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Name')
    number = models.CharField(max_length=255, blank=False, null=False, verbose_name='Number')

    def __str__(self):
        return '{}'.format(self.name)

    class Meta:
        db_table = 'JobPosition'
        verbose_name = 'Job Position'
        verbose_name_plural = 'Job Positions'


class JobAssignment(models.Model):
    person = models.ForeignKey(Person, blank=False, null=False, verbose_name='Person')
    position = models.ForeignKey(JobPosition, blank=False, null=False, verbose_name='Position')
    location = models.ForeignKey(Location, blank=True, null=True, verbose_name='School')
    classification = models.ForeignKey(Classification, blank=True, null=True, verbose_name='Classification')
    start_date = models.DateField(blank=True, null=True, verbose_name='Start Date')
    end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
    effective_date = models.DateField(blank=True, null=True, verbose_name='Effective Date')
    fte = models.CharField(max_length=10, blank=True, null=True, verbose_name='FTE')
    seniority_date = models.DateField(blank=True, null=True, verbose_name='Seniority Date')
    last_start_date = models.DateField(blank=True, null=True, verbose_name='Last Start Date')
    last_pay_date = models.DateField(blank=True, null=True, verbose_name='Last Pay Date')
    entry_date = models.DateField(blank=True, null=True, verbose_name='Position Entry Date')
    record_number = models.IntegerField(default=0, verbose_name='Position Record Number')
    pay_group = models.CharField(max_length=3, blank=True, null=True, verbose_name='Pay Group')
    indicator = models.CharField(max_length=1, blank=True, null=True, verbose_name='Indicator')
    full_or_part_time = models.CharField(max_length=1, blank=True, null=True, verbose_name='Full/Part')
    standard_hours_per_week = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='Standard Hours per Week')
    pay_status = models.CharField(max_length=1, blank=True, null=True, verbose_name='Pay Status')
    comp_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Comp Rate')
    comp_frequency = models.CharField(max_length=10, blank=True, null=True, verbose_name='Comp Freq')
    hourly_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Hrly Rate')
    daily_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Daily Rt')
    rate_code = models.CharField(max_length=10, blank=True, null=True, verbose_name='Rate Code')
    compensation_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Compensation Rate')
    total_cdays = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='TOTAL_CDAYS')
    teacher_hours = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='Teacher Hours')

    def __str__(self):
        return '{} - {}'.format(self.position.name, self.position.number)

    @classmethod
    def current_assignments(cls):
        return cls.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).exclude(person__ssn__isnull=True).exclude(person__current_identity__isnull=True).exclude(person__contact__isnull=True)

    class Meta:
        db_table = 'JobAssignment'
        verbose_name = 'Job Assignment'
        verbose_name_plural = 'Job Assignments'
        ordering = ['location__name', 'person__current_identity__last_name', 'person__current_identity__first_name', 'position__name']

0 个答案:

没有答案