English 中文(简体)
Django模型中一个接收器数据的问题
原标题:Issues loading data from an iterator into a Django Model

我拥有一个网络台,提供即将输入Django模型的数据字标。 我撰写了一份简单的文字,用于测试负荷数据。 它通过压缩字标进行操作,并将每个关键价值输入适当的模型领域(关键人物与各自的模型领域共享姓名)。 虽然我的新模式接受数据,但在数据公布后却未保留。 我可以说明原因。

In [1]: from events.models import Event

In [2]: eventObject = Event() #New model object to hold the item.

In [3]: item = { title :  hellooo ,  description :  just a test ,  eventid :  412212 } #We want to load this item into the eventObject

In [4]: for k in item.keys():
...:     eventObject.k = item[k]
...:     print "eventObject.%s: " % (k) + eventObject.k

eventObject.eventid: 412212 #eventObject received the item s data, as to be expected...
eventObject.description: just a test
eventObject.title: hellooo

In [5]: eventObject #but now eventObject is still empty!
Out[5]: <Event: >

In [6]: eventObject.title #just making sure.
Out[6]:   

In [7]: for k in item.keys():
    eventObject.k = item[k]
    print "eventObject.%s: " % (k) + eventObject.k
    eventObject.save()  #Oh, maybe we need to save it...

eventObject.eventid: 412212
---------------------------------------------------------------------------
IntegrityError                            Traceback (most recent call last)

/home/anthony/Dropbox/Projects/Django/livingCityMap/<ipython console> in <module>()

/usr/local/lib/python2.7/dist-packages/django/db/models/base.pyc in save(self, force_insert, force_update, using)
    458         if force_insert and force_update:
    459             raise ValueError("Cannot force both insert and updating in model saving.")
--> 460         self.save_base(using=using, force_insert=force_insert, force_update=force_update)
    461 
    462     save.alters_data = True

/usr/local/lib/python2.7/dist-packages/django/db/models/base.pyc in save_base(self, raw, cls, origin, force_insert, force_update, using)
    551                 if values:
    552                     # Create a new record.

--> 553                     result = manager._insert(values, return_id=update_pk, using=using)
    554                 else:
    555                     # Create a new record with defaults for everything.


/usr/local/lib/python2.7/dist-packages/django/db/models/manager.pyc in _insert(self, values, **kwargs)
    193 
    194     def _insert(self, values, **kwargs):
--> 195         return insert_query(self.model, values, **kwargs)
    196 
    197     def _update(self, values, **kwargs):

/usr/local/lib/python2.7/dist-packages/django/db/models/query.pyc in insert_query(model, values, return_id, raw_values, using)
1432     part of the public API.
1433     """
1434     query = sql.InsertQuery(model)
1435     query.insert_values(values, raw_values)
-> 1436     return query.get_compiler(using=using).execute_sql(return_id)

/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.pyc in execute_sql(self, return_id)
    789     def execute_sql(self, return_id=False):
    790         self.return_id = return_id
--> 791         cursor = super(SQLInsertCompiler, self).execute_sql(None)
    792         if not (return_id and cursor):
    793             return

/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.pyc in execute_sql(self, result_type)
    733 
    734         cursor = self.connection.cursor()
--> 735         cursor.execute(sql, params)
    736 
    737         if not result_type:

/usr/local/lib/python2.7/dist-packages/django/db/backends/util.pyc in execute(self, sql, params)
    32         start = time()
    33         try:
---> 34             return self.cursor.execute(sql, params)
    35         finally:
    36             stop = time()

/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.pyc in execute(self, query, args)
    42     def execute(self, query, args=None):
    43         try:
---> 44             return self.cursor.execute(query, args)
    45         except Database.IntegrityError, e:
    46             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]

IntegrityError: null value in column "eventid" violates not-null constraint

And the model, just in case you re curious: from django.contrib.gis.db import models

class Event(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    eventid = models.IntegerField(max_length=200)
    genre = models.CharField(max_length=200)
    contact = models.CharField(max_length=200)
    cost = models.CharField(max_length=200)

    venue = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    neighborhood = models.CharField(max_length=200)
    city = models.CharField(max_length=200)


    date = models.DateTimeField()  # This will be replaced by a new class
    time = models.CharField(max_length=200) # This should obviously be datetime and probably exist in it s own class, but first requires the input to be normalized (via serious RegEx magic)
    def __unicode__(self):
        return self.title
最佳回答

您不能以这种方式以变值确定属性。

你们只是安排活动。 目标k = oo和重复.。

for k in item.keys():
    setattr(eventObject, k, item[k])
    print "eventObject.%s: " % (k) + eventObject.k

或者在你的情况下,你只能把这些关键/价值乳制品带入模型构造。

eventObject = Event(**items)
问题回答

暂无回答




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签