我正在尝试对 3 个表进行外部连接,并且想知道我的方法是否正确且有效?
楷模:
class GuestCategory(models.Model):
profile = models.ForeignKey(UserProfile)
category = models.CharField(max_length=30)
class Meta:
db_table = 'guest_category'
class Guest(models.Model):
profile = models.ForeignKey(UserProfile)
guest_category = models.ForeignKey(GuestCategory,
null=True, blank=True, default = None)
first_name = models.CharField(max_length=48, blank=False)
last_name = models.CharField(max_length=48)
invite_list = models.ManyToManyField(GuestList, through='RSVPList')
class Meta:
ordering = ('last_name', 'first_name')
db_table = 'guest'
class GuestDetails(models.Model):
guest = models.OneToOneField(Guest)
email = models.EmailField(max_length=254, blank=True)
...
country = models.IntegerField(choices=Country(), null=True, blank=True)
class Meta:
db_table = 'guest_details'
意见:
class GuestListView(LoginRequiredMixin, ListView):
context_object_name = 'guest_list'
template_name = 'guest/guest_list.html'
def get_queryset(self):
self.guests = Guest.objects.raw("SELECT \
guest.id, \
guest.first_name, \
guest.last_name, \
guest_details.email, \
...
guest_details.country, \
guest_category.category \
FROM guest \
LEFT OUTER JOIN guest_details \
ON guest_details.guest_id = guest.id \
LEFT OUTER JOIN guest_category \
ON guest_category.id = guest.guest_category_id \
WHERE guest.profile_id = %s", [self.request.user.get_profile().id]
)
return self.guests
模板:
<ul>
{% for guest in guest_list %}
<li>{{ guest.first_name }} {{ guest.last_name }}
<ul>
<li>Email: {{ guest.email }}</li>
...
<li>Country: {{ guest.country }}</li>
{% comment %} {{ guest_details.get_country_display }} {% endcomment %}
<li>Category: {{ guest.guest_category }}</li>
<li><a href="{% url 'guests:guest_update' pk=guest.pk %}">Edit</a></li>
<li><a href="{% url 'guests:guest_delete' pk=guest.pk %}">Remove</a></li>
</ul>
</li>
{% endfor %}
</ul>
基本上,用户可以创建客人类别来放置他们的客人,例如朋友、家人。并且在创建客人时,他们可能会或可能不会准备好客人的详细信息,因此在用户创建客人的详细信息之前不会保存。我尝试prefetch_related
在 guest_details 上使用,但如果没有条目,则不会返回来宾。
我想为他们的客人返回多行信息给用户,如下所示:
first_name | last_name | country | category
------------+-----------+---------+----------
Guest | Two | 169 | Friends
Guest | One | 13 | Friends
Guest | Three | 10 | Friends
Guest | Four | |
请注意,客人类别也不是必填字段。我使用左外连接来获取类别和详细信息。但是,当我在浏览器中加载视图时,我注意到由于{{ guest.guest_category }}
. 我可以从 guest_category 表中检索类别,而无需像上面的 SQL 结果中那样使用额外的数据库命中吗?
有没有更好的方法来实现我想要的?我对 SQL 并不陌生,但如果有更多 django-ish 的缓存,那就太棒了。