多个Foriegn键在Django的同桌?

时间:2016-05-14 09:39:47

标签: django database-design django-models

我想在Django中创建一个表单,该表单将数据存储在一个模型中,该模型包含1)总线服务的名称2)源3)目的地4)trip_distance和5)entry_timestamp。

我还想在不同的数据库表中保留服务,源和目标的名称。因此,用户可以在填写表单时从下拉菜单中选择这些。

class Service(models.Model):
    service_name = models.CharField(max_length = 30)
    entry_timestamp = models.DateTimeField(auto_now_add = True)

    def __unicode__(self):
        return self.service_name

class Source(models.Model):
    source_name = models.CharField(max_length = 30)
    entry_timestamp = models.DateTimeField(auto_now_add = True)

    def __unicode__(self):
        return self.source_name

class Destination(models.Model):
    destination_name = models.CharField(max_length = 30)
    entry_timestamp = models.DateTimeField(auto_now_add = True)

    def __unicode__(self):
        return self.destination_name

class EntryForm(models.Model):
    service= models.ForeignKey(Service)
    source = models.ForeignKey(Source)
    destination = models.ForeignKey(Destination)
    trip_distance = models.PositiveIntegerField()
    entry_timestamp = models.DateTimeField(auto_now_add = True)

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

这是我想出的。

现在,当我尝试通过shell创建EntryForm时,我收到以下错误

q = Service.objects.get(pk=1)
>>> q
<Service: Rajasthan Roadways>
q.entryform_set.create(source = 'Midwest',destination = 'Sahara',trip_distance = 10000)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 752, in create
    return super(RelatedManager, self.db_manager(db)).create(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 346, in create
    obj = self.model(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 468, in __init__
    setattr(self, field.name, rel_obj)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 635, in __set__
    self.field.rel.to._meta.object_name,
ValueError: Cannot assign "'Midwest'": "EntryForm.source" must be a "Source" instance.

我怎样才能更好地设计?我可以通过管理员手动创建EntryForm对象然后它可以工作。

在这个django教程中,类似的行有效并且不会出现此错误

>>> q = Question.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]

# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)

为什么我不能同样创建EntryForm对象?另外我想要一个表格来保存数据到这个模型,所以我可以命名它?

1 个答案:

答案 0 :(得分:0)

在评论中,您询问如何设置模型。您可以将SourceDestination分组到一个模型中,称之为Place,因为它们似乎都是指代地点。

class Service(models.Model):
    service_name = models.CharField(max_length = 30)
    entry_timestamp = models.DateTimeField(auto_now_add = True)

    def __unicode__(self):
        return self.service_name

class Place(models.Model):
    source_name = models.CharField(max_length = 30)
    entry_timestamp = models.DateTimeField(auto_now_add = True)

    def __unicode__(self):
        return self.source_name

class Connection(models.Model):
    service= models.ForeignKey(Service, related_name='connections')
    source = models.ForeignKey(Place, related_name='departing_connections')
    destination = models.ForeignKey(Place, related_name='arriving_connections')
    trip_distance = models.PositiveIntegerField()
    entry_timestamp = models.DateTimeField(auto_now_add = True)

仅在您的Connection模型中,您再次将它们分为sourcedestination字段。添加related_name会使其更易于阅读,例如

p = Place.objects.get(pk=1)

from_here = p.departing_connections.all()

this_year = from_here.filter(service__entry_timestamp__year=date.today().year

在添加Connection之前,您需要添加ServicePlace个对象,以便与之相关的连接。