如何根据用户选择的 InlineKeyboardButton 发送 Django 模型对象的详细信息作为答案?

How to send Django model object's details as answer according to the user's choice of InlineKeyboardButton?

我刚开始使用 Django 创建电报机器人。我选择了 python-telegram-bot 库来使用 Django 创建机器人。

我创建了一个 Django 模型,命名为 category:

class category(models.Model):
    name = models.CharField(max_length=250)
    category_id = models.IntegerField()

    def __str__(self):
        return self.name

产品:

class product(models.Model):
    product_category = models.ForeignKey(category, on_delete=models.SET_NULL, blank=True, null=True)
    name = models.CharField(max_length=250)
    cost = models.FloatField()
    img = models.ImageField()

    def __str__(self):
        return self.name

成功创建 InlineKeyboardButtons 并将每个产品模型对象的 id 放置到每个按钮,具有以下功能:

def product(update: Update, context: CallbackContext):
    query = update.callback_query.data

    product_button_list = []
    
    for each in product.objects.select_related().filter(product_category_id = query):
        product_button_list.append(InlineKeyboardButton(each.name, callback_data=each.id))
    reply_markup = InlineKeyboardMarkup(build_menu(product_button_list,n_cols=2))
    update.callback_query.message.edit_text("Mahsulotni tanlang!", reply_markup=reply_markup)

def build_menu(buttons,n_cols,header_buttons=None,footer_buttons=None):
  menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
  if header_buttons:
    menu.insert(0, header_buttons)
  if footer_buttons:
    menu.append(footer_buttons)
  return menu

当用户选择一个名为产品模型对象名称的按钮时,我收到了正确的产品模型对象 ID,通过打印查询进行了测试:

def product_info(update: Update, context: CallbackContext):
    query = update.callback_query.data
    print(query)

    obj = product.objects.filter(pk=query)
    print(obj)

问题:如何根据用户选择的产品向用户回复Django产品模型对象的字段,包括图片?

喜欢:

您选择了一个产品:

产品图片

产品名称

产品成本

这是答案,到目前为止我已经成功了:

filename = 'path_until_media_folder' + str(obj.img.url) 

update.callback_query.bot.send_photo(update.effective_chat.id, photo=open(filename, 'rb'))