Django中同一个表中的多个Foriegn键



我想在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对象?此外,我想要一个表单来将数据保存到这个模型中,那么我能给它起什么名字呢?

在注释中,您询问如何设置模型。您可以将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对象,以便连接与之相关。

最新更新