0
我想檢索與我的ToolTransaction模型上的外鍵的PartyID相關的名字和姓氏字段。我有一個我用來存儲數據的mysql數據庫。我的目標是讓名字出現在適當的交易中,而不是PartyID。我能夠顯示所有活動交易,但我無法將他們的第一個和最後一個名稱顯示出來。我的一些代碼可能對我來說有點不可靠,因此試圖解決這個問題,所以我的道歉。Django外鍵關係和顯示模板
型號:
class Tool(models.Model):
ToolID=models.CharField(max_length=100, primary_key = True, unique=True, db_column=b'ToolID')
Quantity=models.IntegerField(null=False)
Location=models.CharField(max_length=100, null=False)
CategoryID=models.IntegerField(null=True)
Deleted=models.BooleanField(default=0)
objects=models.Manager()
class Meta:
managed=True
db_table='Tool'
def __unicode__(self):
return self.ToolID
def get_absolute_url(self):
return reverse("ToolSearch:toolSearchResults", kwargs={"pk": self.ToolID})
class Party(models.Model):
PartyID=models.AutoField(primary_key=True, db_column=b'PartyID')
FirstName=models.CharField(max_length=100, null=False)
LastName=models.CharField(max_length=100, null=False)
PhoneNumber=models.CharField(max_length=25, null=False)
Organization=models.CharField(max_length=100, null=True)
Deleted=models.BooleanField(default=0)
objects=models.Manager()
class Meta:
managed=True
db_table='Party'
def __unicode__(self):
return str(self.PartyID)
def get_absolute_url(self):
return reverse("ToolSearch:borrowerUpdate", kwargs={"pk": self.PartyID})
class ToolTransaction(models.Model):
CheckOutID=models.AutoField(primary_key=True)
ToolID=models.ForeignKey(Tool, db_column='ToolID', on_delete=models.CASCADE, related_name='ToolID_fk',)
PartyID=models.ForeignKey(Party, db_column='PartyID', on_delete=models.CASCADE, related_name='PartyID_fk',)
Quantity=models.IntegerField(null=False)
CheckOutDate=models.DateField(null=False, default=datetime.datetime.now)
CheckInDate=models.DateField(null=True)
Deleted=models.BooleanField(default=0)
objects=ActiveTransactionManager()
#objects=models.Manager()
class Meta:
managed=True
db_table='ToolTransaction'
ordering=('CheckOutID',)
def __unicode__(self):
return str(self.CheckOutID)
def get_absolute_url(self):
return reverse("ToolSearch:toolCheckin", kwargs={"pk": self.CheckOutID})
查看:
def tool_transaction_search(request):
instance=ToolTransaction.objects.all()
ToolTransaction.objects.filter(PartyID=instance.PartyID).select_related()
context={
"Transactions": instance,
}
return render(request, "tooltransactionsearch.html", context)
模板:
{% for tran in Transactions %}
<h5>
CheckOutID: <a href="{{ tran.get_absolute_url }}"> {{tran.CheckOutID}} </a> <br>
Name: {{tran.Party.FirstName}} {{tran.LastName}} <br>
PartyID: {{tran.PartyID}} <br>
ToolID: {{tran.ToolID}} <br>
CheckOutDate: {{tran.CheckOutDate}} <br>
CheckInDate: {{tran.CheckInDate}} <br> <br>
</h5>
{% endfor %}
任何幫助將不勝感激!