使用__str__方法获取django对象

发布于 2025-02-13 03:54:22 字数 446 浏览 1 评论 0原文

我有这个称为子句的Django模型,并且我有一个为其定义的__ str __方法。 现在,我的表单显示了该子句的下拉列表,但是当我发布该表单时,它将这些子句转换为字符串,而我需要rales objects。如果我有.__ str __(),是否有办法获得子句? 模型:

class Clause(models.Model):
   reference_number = models.CharField(max_length=1000)
   title            = models.CharField(max_length=1000)
   
   def __str__(self):
       return self.reference_number + ": " + self.title

I have this Django model called Clause and I have a __str__ method defined for it.
Now I have a form that displays a dropdown for the clauses, but when I POST that form, it converts those clauses to strings, whereas I need the Clause objects. Is there a way to get the clause if I have it's .__str__()?
The model:

class Clause(models.Model):
   reference_number = models.CharField(max_length=1000)
   title            = models.CharField(max_length=1000)
   
   def __str__(self):
       return self.reference_number + ": " + self.title

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听你说爱我 2025-02-20 03:54:22

在您的__ str __方法中,您可能已经使用了子句的名称,标题或其他属性。您可以使用该属性获取特定对象。

如果您的条款定义是如此:

class Clause(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.title}"

在您的视图函数中:

# Get the requested_title from the request
Clause.objects.get(title=requested_title)

In your __str__ method you probably have used the name, title or another attribute of the Clause. You can use that attribute to get the particular object.

If your Clause definition is like so:

class Clause(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.title}"

In your view function:

# Get the requested_title from the request
Clause.objects.get(title=requested_title)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文