![](/img/trans.png)
[英]How to serialize joined tables if there are 2 Foreign Key to join the same table with Django Rest Framework?
[英]How to print data in template django of a diffrent table joined by foreign key?
大家好,我有两个模型第一个如下:
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
bargainprice = models.FloatField(default=0)
discount_price = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
image = models.ImageField()
我使用以下视图获取此模型数据:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
在 product.html 中,我正在访问这样的 Item 对象:
<span class="mr-1">
<del>₹ {{ object.price }}</del>
</span>
<span>₹ {{ object.discount_price }}</span>
{% else %}
<span> ₹ <span id="pp">{{ object.price }}</span></span>
等等..
这里一切正常。 但是当我创建以下模型时出现问题:
class BargainModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
itemId = models.IntegerField()
bprice = models.FloatField()
如前所述,我用外键加入了这个。 **我想要做的是在同一用户的 product.html 中打印“ bprice ”,但我无法做到 ** 任何人都可以帮我解决这个问题,我是 Django 的新手。 提前致谢
在这种情况下,您需要像这样导入 User
from django.contrib.auth.models import User
class BargainModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
itemId = models.ForeignKey(Item, on_delete=models.CASCADE)
bprice = models.FloatField()
在 product.html 中,您可以调用 BargainModel 的模型,它也包含带有用户的 Item
这是更好地工作,一个ForeignKey
,因为这将保证引用完整性。 你这样shoudl定义BargainModel
为:
from django.conf import settings
class Bargain(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
item = models.ForeignKey(
Item,
on_delete=models.CASCADE
)
bprice = models.FloatField()
class Meta:
constraints = [
models.UniqueConstraint(fields=['item', 'user'], name='unique_user_item')
]
在DetailView
,我们可以查看是否有给定项目和用户的Bargain
记录:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_bargain(self):
if self.request.user.is_authenticated():
return Bargain.objects.filter(item=self.object, user=request.user).first()
然后你可以用:
{{ view.get_bargain.bprice }}
如果有相关的Bargain
,则会显示相应的bprice
。
注意:型号通常没有
Model
后缀。 因此,最好将重命名为BargainModel
Bargain
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.