Room(子)からHotel(親)を外部キーにて参照したいのですが、
クエリで記載するとなぜかHotel(親)のデータがテンプレートに表示されません。
#model/Hotel.py from django.db import models from django.utils import timezone class Hotel(models.Model): class Meta: db_table = 'hotel' hotel_id = models.CharField(max_length=10, unique=True, primary_key=True) hotel_name_ja = models.CharField(max_length=255) hotel_name_en = models.CharField(max_length=255, null=True) def __str__(self): return self.hotel_name
#motel/Room.py from django.db import models from django.utils import timezone from newbook.models import Hotel, Plan class Room(models.Model): class Meta: db_table = 'room' unique_together = (('hotel_id','room_id')) hotel_id = models.ForeignKey(Hotel,on_delete=models.CASCADE) room_id = models.CharField(max_length=10) room_name = models.CharField(max_length=10) plan_id = models.ManyToManyField(Plan) def __str__(self): return self.room_name
#views.py from django.shortcuts import render,get_object_or_404, redirect from django.utils import timezone from newbook.models import Hotel, Room from django.views import View class TestView(View): def get(self, request, *args, **kwargs): rooms = Room.objects.order_by('room_id') roomHotels = Room.objects.select_related().all() context = { 'rooms':rooms, 'roomHotels':roomHotels, } return render(request, 'reserve/testpage.html', context) testpage = TestView.as_view()
#template {% for roomHotel in roomHotels %} <div class="post"> <div class="date"> <p>ホテル名: {{ roomHotel.hotel_name_ja }}</p> <p>ホテル名英語: {{ roomHotel.hotel_name_en }}</p> <p>ルーム名: {{ roomHotel.room_name }}</p> </div> </div> {% endfor %}
エラー内容
Cannot resolve keyword 'room_id' into field. Choices are: hotel_id, hotel_name, hotel_name_en, room
debug_toolbarで記述されたSQL文は下記で、
こちらをphpMyAdminで実行したら問題なく表示されました。
#SQL文 SELECT `room`.`id`, `room`.`hotel_id_id`, `room`.`room_id`, `room`.`room_name`, `hotel`.`hotel_id`, `hotel`.`hotel_name_ja`, `hotel`.`hotel_name_en` FROM `room` INNER JOIN `hotel` ON (`room`.`hotel_id_id` = `hotel`.`hotel_id`)
紐付けの方法がなにか抜けているのでは?と思うのですが、アドバイスいただければ幸いです。
また、別件になりますが、
id以外を外部キーとして紐付けたいのですが(今回だとhotel_id (string))
調べてもなかなかヒットせず・・
方法ご存知でしたら教えていただければ幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/23 08:03