Django 查询 - 将用户类与 Telegram Bot 的 OnetoOnefield 类连接起来

Posted

技术标签:

【中文标题】Django 查询 - 将用户类与 Telegram Bot 的 OnetoOnefield 类连接起来【英文标题】:Django query - connect User Class with OnetoOnefield class for Telegram Bot 【发布时间】:2020-10-11 11:37:54 【问题描述】:

我在从与用户类连接的自定义类中查询属性时遇到问题。

我的目标:我想通过电报机器人每次鼠标点击在我的网站上向我的手机发送消息(消息有效) - 为此我需要用户的聊天 ID

由于有多个用户,我将 chat_id 存储在我创建的新模型中,该模型通过 onetoonefield 链接到 User 模型:

User = get_user_model()

class TelegramProfile(models.Model):
    name = models.CharField(default="",max_length=200,blank=True,unique=True)
    user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="user_id")
    telegram_chat_id = models.CharField(max_length=40,default="",editable=True,blank=True,unique=True)
   
    def __str__(self):
        return str(self.name)

我的用户模型是内置模型:

class User(auth.models.User, auth.models.PermissionsMixin):

def __str__(self):
    return f"@self.username"

因此,在我的 views.py 文件中,我具有获取消息的函数(另一个名为 Recipe 的模型类 - 我通过主键识别它)和属于特定用户的 chat_id:

  def bot(request,msg,chat_id,token=my_token):
        bot=telegram.Bot(token=token)
        bot.send_message(chat_id=chat_id, text=msg)



  def home(request,pk):
      recipe = get_object_or_404(Recipe,pk=pk)
      user = request.user
      chat_id = User.objects.get(TelegramProfile.telegram_chat_id,user) #with this query I try to grab the chat_id of the logged in user
      ingredients = recipe.ingredients
      ingredients = ingredients.split("<p>")
      ingredients = "\n".join(ingredients)
      ingredients = strip_tags(ingredients)
      bot(request,ingredients,chat_id)
      return render(request,"recipes/send_recipe.html")

所以我的问题是:

-如何查询 chat_id 以便: 特定登录用户的chat_id将被调用,以便我可以将其插入机器人功能以将消息发送到此特定ID?

我还是 django 的新手,所以我还在学习查询,提前非常感谢!!!

【问题讨论】:

你的错误到底是什么? 【参考方案1】:

编辑:能够自己解决:

def send_recipe(request, pk):
  try:
    if request.method == "POST":
        data_option = str(request.POST[
                              "testselect"])  # testselect is the select form in recipe_detail.html with which I select 1 of the 2 options
        if data_option == "Ingredients":
            recipe = get_object_or_404(Recipe, pk=pk)
            recipe_name = recipe.name.upper()
            ingredients = recipe.ingredients
            ingredients = ingredients.split("<p>")
            ingredients = "\n".join(ingredients)
            ingredients = strip_tags(ingredients)
            message = f"recipe_name: \n ingredients"

            user = TelegramProfile.objects.get(
                user=request.user)  # use get instead of filter! filter returns the name but can t use it as object, with get I get the object and I can use the attributes on it!
            chat_id = user.telegram_chat_id
            bot(request, message, chat_id)
            return render(request, "recipes/send_recipe.html")
        elif data_option == "Ingredients & Description":
            recipe = get_object_or_404(Recipe, pk=pk)
            recipe_name = recipe.name.upper()  # recipe name
            ingredients = recipe.ingredients
            ingredients = ingredients.split("<p>")
            ingredients = "\n".join(ingredients)
            ingredients = strip_tags(
                ingredients)  # we grab recipes ingredients and mute them, split at p tag, then add a new line and join them then remove tags
            recipe_description = recipe.description
            recipe_description = recipe_description.split("<p>")
            recipe_description = "\n".join(recipe_description)
            recipe_description = strip_tags(recipe_description)
            message = f"recipe_name: \n ingredients \n \n recipe_description"

            user = TelegramProfile.objects.get(user=request.user)
            chat_id = user.telegram_chat_id
            bot(request, message, chat_id)
            return render(request, "recipes/send_recipe.html")
    else:
        return render(request, "recipes/create_telegram.html")
  except Exception:
    return render(request, "recipes/create_telegram.html")

【讨论】:

以上是关于Django 查询 - 将用户类与 Telegram Bot 的 OnetoOnefield 类连接起来的主要内容,如果未能解决你的问题,请参考以下文章

使用外键查询 Django 模型并获取登录用户

当 bean 类与一对多注释链接时,使用 hibernate 在 db 上选择查询:

元类与 Django 中的 modelformset_factory 冲突

drf之视图类与路由

Django如何在查询集中标记用户特定的对象以发送到模板?

将查询集数据传递给另一个查询 django