![](/img/trans.png)
[英]How can I make a connection through a ForeignKey prefetch_related?
[英]How I can get related model for custom column in admin list_display with prefetch_related?
嗨,我有兩個模型通過第三個模型進行m2m
鏈接:
class Group(UsefulAbstractModel):
hotels = models.ManyToManyField(
Hotel,
through='HotelDetails',
related_name='groups', )
class Hotel(UsefulAbstractModel):
name = models.CharField(
max_length=255,)
class HotelDetails(models.Model):
hotel = models.ForeignKey(
Hotel,
related_name='hotel_details', )
group = models.ForeignKey(
Group,
related_name='hotel_details', )
num = models.IntegerField(
validators=[
MaxValueValidator(2),
MinValueValidator(1), ], )
所有組都有兩個帶有數字1和2的酒店鏈接。我需要在管理組界面中顯示它。 我為每個酒店創建兩個自定義列:
class GroupAdmin(admin.ModelAdmin):
def first_hotel(self, instance):
return instance.hotel_details.filter(num=1).first().hotel
def second_hotel(self, instance):
return instance.hotel_details.filter(num=1).first().hotel
但是對於每個實例,我現在有2個附加查詢。
我試圖覆蓋queryset
方法,但沒有幫助:
def queryset(self, request):
return super(GroupAdmin,self).queryset(request).prefetch_related('hotels')
問題是您正在使用filter(num=1)
過濾預取的結果。 這導致Django進行新查詢。
您可以使用Prefetch
對象來獲取正確的查詢集。 注意,您應該覆蓋模型管理員的get_queryset
方法,而不是queryset
。
def get_queryset(self, request):
return super(GroupAdmin,self).get_queryset(request).prefetch_related(
Prefetch('hotel_details', queryset=HotelDetails.objects.filter(num=1).select_related('hotel'), to_attr='hotel_details_num1'),
)
然后,更改模型管理方法以使用新的查詢集,例如:
def first_hotel(self, instance):
return instance.hotel_details_num1.first().hotel
有關更多關於prefetch_related
和Prefetch
對象的信息,請參閱文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.