所以我有一个KeyRequest
模型和一个KeyInstance
模型。一个KeyRequest
只能引用一个KeyInstance
,反之亦然。每个KeyInstance
都有uuid
和status
。
我想访问uuid
和KeyRequest
这是我的models.py:
class KeyInstance(models.Model):
keyrequest = models.OneToOneField('KeyRequest', verbose_name='Key requests', on_delete=models.SET_NULL, null=True, blank=True, related_name='request')
LOAN_STATUS = (
('a', 'Available'),
('o', 'On loan'),
('r', 'Reserved'),
)
status = models.CharField(max_length=1, choices=LOAN_STATUS, help_text='Key availability', verbose_name="Key status", blank=True)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular key")
class Meta:
ordering = ["due_back"]
permissions = (("can_mark_returned", "Set key as returned"),)
@property
def is_overdue(self):
if self.due_back and date.today() > self.due_back:
return True
return False
def __str__(self):
"""
String for representing the Model object
"""
return '{1} ({0})'.format(self.id,self.roomkey.room_name)
def get_absolute_url(self):
"""
Returns the url to access a detail record for this book.
"""
return reverse('keys',args={'pk':self.id})
...
class KeyRequest(models.Model):
"""
Model that will hold the key requests
"""
roomkey = models.ForeignKey('RoomKey',verbose_name="Room", on_delete=models.SET_NULL, null=True)
def __str__(self):
"""
String for representing the Model object
"""
return '{2}-{0} ({1})'.format(self.roomkey.room_name, self.date_requested, self.requester)
def get_absolute_url(self):
return reverse('key-request-detail', args=[str(self.id)])
这是我的views.py:
class KeyRequestDetailView(generic.DetailView):
model = KeyRequest
template_name = "catalog/roomkey_request_detail.html"
def RequestDetail(request):
num_keyinstances_available = KeyInstance.objects.filter(status__exact='a').count()
return render(
request,
'key-request-detail',
context = {'num_key_available':num_keyinstances_available},
)
这是我的模板
{{ keyrequest.request.id }}
{{ num_key_available }}
有谁能告诉我这样做的正确方法?
答案 0 :(得分:0)
看看你能做些什么。我相信它会以某种方式指向正确的方向。评论部分太长了。 上下文字典中的所有内容都将在您的模板中提供。您可以在上下文字典中放置任意数量的内容。
class KeyRequestDetailView(generic.DetailView):
model = KeyRequest
template_name = "catalog/roomkey_request_detail.html"
def get_object(self, queryset=None):
pk = self.kwargs.get('pk', None) # I assume you're using pk to lookup the KeyRequest
keyrequest_instance = KeyRequest.objects.get(pk=pk)
# But if there is no such keyrequest instance you have to handle the error somehow
context = {}
context['keyrequest'] = keyrequest_instance # the actual keyrequest
context['num_key_available'] = KeyInstance.objects.filter(status__exact='a').count() # total number of 'available' keys
key_request_id = keyrequest_instance.keyinstance.id # id of each keyrequest reference from the instance it is tied to
key_request_status = keyrequest_instance.keyinstance.status # status of each keyrequest reference from the instance it is tied to
return render(request, "catalog/roomkey_request_detail.html", context)