請教各位前輩
我用Python+Django的架構,我想在畫面的"備註"欄位,顯示出正確的內容,但不知道要怎麼去撈PK對應到FK的資料,一直都撈錯 @@
狀況問題:我從"SoftWare"這張表,去對應到 "Memo"這張表,要去db內撈出資料回來,但都會變成撈到 "Memo"的id,抓到的內容就不是我要的資料內容.
我該怎麼修改才對? (舉例:software_id : 4 要撈出 Memo id: 8 資料內容)
謝謝各位前輩
附上code及db和畫面圖片
畫面
db
Models - Memo
class Memo(models.Model):
notes = models.TextField()
software = models.ForeignKey(Software, on_delete=models.CASCADE)
timestamp = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.notes
Models - Software
class Software(models.Model):
STATUS_CHOICES = [
(0, '規劃中'),
(1, '開發中'),
(2, '使用中'),
(3, '已廢棄')
]
name = models.CharField(max_length=100, verbose_name="系統名稱")
url = models.CharField(max_length=100, verbose_name="系統網址")
status = models.PositiveIntegerField(default=0, choices=STATUS_CHOICES, verbose_name="目前狀態")
company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="開發公司或單位")
team = models.ForeignKey(Team, on_delete=models.DO_NOTHING, verbose_name="所屬組別")
def __str__(self):
return self.name
Templates
<form method="POST" name="myform" action="." >
{% csrf_token %}
<table class="table table-striped">
<tr>
<td align=right>新增備註:</td>
<td>
<input type=text size=50 name="notes" value='{{target_Memo.notes}}'>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type=submit value="送出">
</td>
</tr>
</table>
</form>
{% endblock %}
Views
def add_showmemo(request,id=None,logmemo=None):
logged_user = User.objects.get(username=request.user.username)
logged_user = UserProfile.objects.get(user=logged_user)
if request.method=="POST":
unit = Memo.objects.get('notes')
try:
target_Memo = Memo.objects.get(id=id)
#target_Memo.save()
except Exception as e:
print(e)
return redirect("/showdetail/")
return render(request, "add_showmemo.html", locals())
關於Foriegn key可以先看看這篇
按上述的舉例
(舉例:software_id : 4 要撈出 Memo id: 8 資料內容)
這樣不知道有沒有達到你想做到的事情
try:
#先取出software表的id
id = Software.objects.get(pk=4)
#在Memo表中秀出符合software_id的資料
target_Memo = Memo.objects.get(software_id=id)