使用ManyToMany的models.py并通过shell脚本逐步添加数据

时间:2009-08-15 02:10:28

标签: django django-models

第一篇文章到stackoverflow我做了一个搜索,然后干了。我也拥有 django书(Forcier,Bissex,Chun)他们没有解释怎么做 这个。总之,我无法弄清楚如何通过进程添加数据 一个到ManyToMay模型的python shell脚本..

from django.db import models
from django.contrib import admin

class Client(models.Model):
  client        = models.CharField(max_length=256, primary_key=True)
  access        = models.DateField()
  description   = models.TextField()
  host          = models.CharField(max_length=256)
  lineEnd       = models.CharField(max_length=256)
  options       = models.TextField()
  owner         = models.CharField(max_length=100)
  root          = models.CharField(max_length=256)
  submitOptions = models.CharField(max_length=256)
  update        = models.DateField()
  def __unicode__(self):
    return str(self.client)
admin.site.register(Client)


class Change(models.Model):
  """This simply expands out 'p4 describe' """
  change        = models.IntegerField(primary_key=True)
  client        = models.ManyToManyField(Client)
  desc          = models.TextField()
  status        = models.CharField(max_length=128)
  def __unicode__(self):
    return str(self.change)
admin.site.register(Change)

这是我的工作,但我不知道如何添加 多对多。我似乎无法弄清楚如何逐步调用它。 我知道SQL中的行存在。

--- massImport.py ---

# Assume the client "clientspec" exists.  I know how to create that if 
neeeded. 
changes = [ { 'change': 123, 'desc': "foobar", status': "foobar", 
client': "clientspec", }] 
for item in changes: 
  entry = Change( 
            change    = item['change'], 
            desc    = item['desc'], 
            status    = item['status'], 
            # client    = Client.objects.filter(client=item['client']) 
            ) 
  entry.save() 

任何人都可以告诉我我的方式错误在哪里。我真的 欣赏它。 谢谢!!

3 个答案:

答案 0 :(得分:2)

原来蒂亚戈非常接近..

# Assume the client "clientspec" exists.  I know how to create that if 
neeeded. 
changes = [ { 'change': 123, 'desc': "foobar", status': "foobar", 
client': "clientspec", }] 
for item in changes: 
  entry = Change()
  entry.change  = item['change']
  entry.desc    = item['desc']
  entry.status  = item['status']
  entry.time    = datetime.datetime.fromtimestamp(float(item['time']))
  entry.client.add(Client.objects.get(client=item['client']))
  entry.save()

所以..我会给蒂亚戈提供道具

答案 1 :(得分:0)

.filter返回一个列表,当您需要的是单个对象时,您应该使用.get(client=item['client'])

答案 2 :(得分:0)

我尝试了代码但是我收到了错误

ValueError: "<Change: 123 -- foobar>" needs to have a value for field "change" before this many-to-many relationship can be used

Manytomany(entry.client.add)只能在保存字段后使用,即entry.save()

可能有很多客户,所以你可以使用:

changes = [{'change': 123, 'desc': "foobar", 'status': "foobar", 
'client': ("client1","client2"),},{......] 
for item in changes: 
    entry = Change( 
        change    = item['change'], 
        desc    = item['desc'], 
        status    = item['status'],)
    entry.save()
    for c in item['client']:
        entry.client.add(Client.objects.get(client=c))