簡體   English   中英

Python用一對多關系填充數據庫

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

我是初學者,所以請放輕松。 我正在編寫腳本,以便在決定刪除數據庫時不必繼續輸入數據。 我的整個腳本運行良好,除非要處理一對多關系。 它不會保存到數據庫。 誰能告訴我我做錯了什么,或指出正確的方向嗎?

腳本:

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')

模型:

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

那不是models.ForeignKey字段在Django中的工作方式。 您需要獲取Category對象的實例,並將其分配給u.instrumentCategory

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

您可以嘗試:

u.instrumentCategory_id = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM