Django:用new foreign_key更新模型

时间:2018-05-04 06:33:43

标签: django

我使用模型表单管理器创建了一个表单。在保存我的TransactionProfile ModelForm之前,我想将它与订单模型连接起来。当我打印session_order_id时它是正确的id,但是当我在控制台中打印时,self.order_set.get总是为空。任何人都可以帮助我吗?你能不能像我这样做的那样解决它,还是有更干净的方法?

在我的views.py中,我有以下内容:

t = transaction_profile.save(commit=False)
t.update_order_with_transaction_profile(session_order_id)
t.save()

交易/ models.py

class TransactionProfile(models.Model):
    email           = models.EmailField()
    address_line_1  = models.CharField(max_length=120)
    address_line_2  = models.CharField(max_length=120, null=True, blank=True)
    city            = models.CharField(max_length=120)
    country         = models.CharField(max_length=120)
    state           = models.CharField(max_length=120)
    postal_code     = models.CharField(max_length=120)
    update          = models.DateTimeField(auto_now=True)
    timestamp       = models.DateTimeField(auto_now_add=True)
    customer_id     = models.CharField(max_length=120, null=True, blank=True)

    def update_order_with_transaction_profile(self, session_order_id):
            # In ModelManager or just in class TransactionProfile
            o = self.order_set.get(order_id=session_order_id)
            o.transaction_profile = self
            o.save()

订单/ models.py

class Order(models.Model):
    order_id                = models.CharField(max_length=10, unique=True)
    customer_key            = models.CharField(max_length=10, unique=True)
    updated                 = models.DateTimeField(auto_now=True)
    timestamp               = models.DateTimeField(auto_now_add=True)
    transaction_profile     = models.ForeignKey(TransactionProfile, blank=True, null=True, on_delete=models.CASCADE)

1 个答案:

答案 0 :(得分:1)

在将对象用作外键之前,需要将对象保存到DB。由于您的代码import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { public currentEpisode: any = {}; currentIndex: number = -1; episodes = [ { title: 'Winter Is Coming', director: 'Tim Van Patten' }, { title: 'The Kingsroad', director: 'Tim Van Patten' }, { title: 'Lord Snow', director: 'Brian Kirk' }, { title: 'Cripples, Bastards, and Broken Things', director: 'Brian Kirk' }, { title: 'The Wolf and the Lion', director: 'Brian Kirk' }, { title: 'A Golden Crown', director: 'Daniel Minahan' }, { title: 'You Win or You Die', director: 'Daniel Minahan' }, { title: 'The Pointy End', director: 'Daniel Minahan' } ]; showNext(): void { this.currentIndex = (this.currentIndex + 1) == this.episodes.length ? 0 : this.currentIndex + 1; this.currentEpisode = this.episodes[this.currentIndex]; } ngOnInit() { this.showNext() } } 未保存在数据库中,t将无效。

而不是update_order_with_transaction_profile,它只提供与特定配置文件相关的订单(新对象的空列表),您可以直接在self.order_set模型上查询,请注意您需要保存Order firts:

transaction_profile