简体   繁体   English

Python用一对多关系填充数据库

[英]Python populating a database with one-to-many relationship

I'm a beginner, so please go easy on me. 我是初学者,所以请放轻松。 I am working on a script so that I don't have to keep entering in data when I decide to drop the database. 我正在编写脚本,以便在决定删除数据库时不必继续输入数据。 My entire script works well, except when I'm dealing with a one-to-many relationship. 我的整个脚本运行良好,除非要处理一对多关系。 It will not save to the database. 它不会保存到数据库。 Can anyone tell me what I am doing wrong or point me in the right direction? 谁能告诉我我做错了什么,或指出正确的方向吗?

SCRIPT: 脚本:

try:
 pmod.Instrument.objects.get(title='kjkjsdfsadfs')
except pmod.Instrument.DoesNotExist:
 u = pmod.Instrument()
 u.title = 'Bach 42 Trombone'
 u.price = 550.00
 u.soundDescription = 'Good'
 u.functionalityDescription = 'Good'
 u.damageDescription = 'Good'
 u.accessoryDescription = 'Good'
 u.customerName = 'Jake'
 u.customerEmail = 'ks@gmail.com'
 u.instrumentCategory = 1
 print('Good2')
 u.save()

 print('Instrument1 saved')

MODEL: 模型:

class Category(models.Model):
    instrumentCategory=models.CharField(max_length=50,blank=True,null=True)
    def __str__(self):
        return self.instrumentCategory

class Instrument(models.Model):
    title = models.CharField(help_text='title',max_length=50,blank=True,null=True)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    soundDescription=models.CharField(max_length=1000,blank=True,null=True)
    functionalityDescription=models.CharField(max_length=1000,blank=True,null=True)
    damageDescription=models.CharField(max_length=1000,blank=True,null=True)
    accessoryDescription=models.CharField(max_length=1000,blank=True,null=True)
    customerName=models.CharField(max_length=50,blank=True,null=True)
    customerEmail=models.EmailField(max_length=254,help_text='Enter valid email address')
    instrumentCategory=models.ForeignKey(Category)

u.instrumentCategory = 1

That's not how a models.ForeignKey field works in Django. 那不是models.ForeignKey字段在Django中的工作方式。 You need to get an instance of the Category object and assign that to u.instrumentCategory . 您需要获取Category对象的实例,并将其分配给u.instrumentCategory

u.instrumentCategory = pmod.Category.objects.get(id=1)

You may try : 您可以尝试:

u.instrumentCategory_id = 1 u.instrumentCategory_id = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM