在我的项目流程中,我首先在Orders中创建一个数据库条目。此时,foreign_key transaction_profile保持为空。稍后在checkout_page视图中,创建了transaction_profile get。
在transaction_profile.save()发生之后,我想将新创建的Transaction_Profile与订单模型条目连接,其中Order.objects.filter(order_id = request.session ['order_id'])。
我现在正在努力完成这项工作。这里的任何人如何帮助我找到正确的轨道?
结帐> views.py
def checkout_page(request):
if request.POST:
transaction_profile = TransactionProfileModelForm(request.POST)
if transaction_profile.is_valid():
transaction_profile.save()
o = Order.objects.filter(order_id=request.session['order_id'])
#if qs.count() == 1:
o.transaction_profile.add(transaction_profile)
else:
transaction_profile = TransactionProfileModelForm()
context = {
'transaction_profile': transaction_profile,
}
[...]
交易> 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)
def __str__(self):
return self.email
订单> models.py
class Order(models.Model):
order_id = 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)
答案 0 :(得分:1)
您必须先保存实例并将其分配给Order
对象:
if request.POST:
transaction_profile = TransactionProfileModelForm(request.POST)
if transaction_profile.is_valid():
instance = transaction_profile.save(commit=False)
instance.save()
o = Order.objects.get(order_id=request.session['order_id'])
o.transaction_profile = instance
o.save()