为Django设计车辆进入模型

时间:2016-05-22 12:26:56

标签: python django database models

我正在设计一个简单的应用程序,记录通过其详细信息点进入的车辆数量。然后生成不同服务/车辆/等的报告。我想出了一个样本模型。

from django.db import models

# Create your models here.

class Service(models.Model):
    service_name = models.CharField(max_length = 60)
    timestamp = models.DateTimeField(auto_now_add = True,auto_now = False)

    def __unicode__(self):
        return self.service_name

class Place(models.Model):
    place_name = models.CharField(max_length = 120)
    state = models.CharField(max_length=60)
    timestamp = models.DateTimeField(auto_now_add = True,auto_now = False)

    def __unicode__(self):
        return self.place_name

class Connection(models.Model):
    vehicle_no = models.CharField(max_length = 15)
    service= models.ForeignKey(Service)
    source = models.ForeignKey(Place,related_name = 'source')
    destination = models.ForeignKey(Place,related_name = 'destination')
    trip_distance = models.PositiveIntegerField()
    entry_timestamp = models.DateTimeField(auto_now_add = True,auto_now = False)

    def __unicode__(self):
        return self.vehicle_no 

class GlobalOption(models.Model):
    config_option = models.CharField(max_length=120)
    value = models.CharField(max_length = 60)

Admin.py

from django.contrib import admin
from .models import Connection,Service,Place,GlobalOption
from .forms import ConnectionForm
# Register your models here.


class ConnectionAdmin(admin.ModelAdmin):
    form = ConnectionForm
    list_display = ('vehicle_no','service','source','destination','trip_distance','Connection_timestamp')
    list_filter = ['Connection_timestamp']
    search_fields = ['service__service_name','vehicle_no']

class OptionAdmin(admin.ModelAdmin):
    fields = ['config_option','value']
    list_display = ('config_option','value')

class ConnectionInline(admin.TabularInline):
    model = Connection
    extra = 1

class PlaceAdmin(admin.ModelAdmin):
    list_display = ['place_name','timestamp']
    class Meta:
        Model = Place

class ConnectionInline(admin.TabularInline):
    model = Connection
    extra = 1

class ServiceAdmin(admin.ModelAdmin):
    list_display = ['service_name','timestamp']
    class Meta:
        Model = Service
    inlines = [ConnectionInline]


admin.site.register(Connection,ConnectionAdmin)
admin.site.register(Service,ServiceAdmin)
admin.site.register(Place,PlaceAdmin)
admin.site.register(GlobalOption,OptionAdmin)

但是在管理员中,每当我添加连接时,都可以拥有相同的源位置和目标位置。我不要那个。另外,如何在选择源后动态生成目的地选择列表?

因为,此应用只会有传入连接,更好的设计决策是为源和目的地设置单独的模型吗?

1 个答案:

答案 0 :(得分:0)

如果您不想选择相同的来源/目的地,可以在表格的clean()方法中处理。

你可以产生选择&根据您的源/目标模型缓存它们,您的设计看起来没问题,但请记住创建单独模型的选项。我做的类似于允许基于表的各列中的值进行选择;

class GetResults(forms.ModelForm):

    @staticmethod
    def get_choices(event_year):

        key = FORM_CHOICES_CACHE_KEY.format(
            year=event_year
        )
        choices = cache.get(key)

        if choices:
            return choices

        age_categories = set()
        events = set()

        for age_category, event in Result.objects.values_list('age_group', 'event').distinct():
            if age_category:
                age_categories.add(age_category)
            if event:
                events.add(event)

        age_categories = [
            (ac, ac) for ac in sorted(age_categories, key=lambda a: a.lower())
        ]
        events = [
            (e, e) for e in sorted(events, key=lambda a: a.lower())
        ]

        choices = (
            age_categories,
            events
        )

        cache.set(key, choices, FORM_CHOICES_CACHE_LENGTH)

        return choices

    def __init__(self, event_year, *args, **kwargs):

        self.event_year = event_year
        if not self.event_year:
            self.event_year = datetime.datetime.utcnow().year

        age_categories, events = self.get_choices(event_year)

        super(GetResults, self).__init__(*args, **kwargs)

        self.fields['age_group'] = forms.ChoiceField(choices=age_categories)
        self.fields['age_group'].label = _("Age category")

        self.fields['event'] = forms.ChoiceField(choices=events)
        self.fields['event'].label = _("Event")

    class Meta:
        model = Result