Django中的自定义链接
这是我的初始代码,
class Article(models.Model):
article_author = models.CharField(max_length=12)
article_name = models.CharField(max_length=60)
article_body = models.TextField()
article_date = models.DateTimeField(auto_now_add=True)
article_tags = models.CharField(max_length=25, choices=tags_, null=True)
article_link = make_link()
事实证明它不会添加到数据库中,也无法进行迁移(因为它不是.models的一部分)。  (我希望将链接自动作为创建文章类的实例,没有用户的实例),
我可以将其制成charfield,然后用该功能替换那里的任何内容,但这似乎是一个草率的解决方案,也是如此'将为默认管理面板提供一个无用的字段。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
链接
属性添加到您的模型,因为您可以像
acrate.link
一样轻松地访问它。you can add a
link
property to your model asthen you can access it easily just like
article.link
我建议在
save()
上生成链接,然后将其存储在charfield
中,用editable = false = false
,就像Willem所建议的那样。文档: https://djangoproject.com/4.0 /ref/models/fields/#可编辑
或,如果文章链接遵循某些逻辑,则可能无需生成并存储链接,但可以作为属性即时访问它。
Django具有
get_absolute_url()
方法,而不是属性,用于为模型对象生成URL:I would suggest generating the link on
save()
and store it in aCharField
witheditable=False
, just like Willem suggested.Docs: https://docs.djangoproject.com/en/4.0/ref/models/fields/#editable
Or, if the article link is following some logic, there might be no need to generate and store the link, but access it on the fly as a property.
Django has the
get_absolute_url()
method, not a property, for generating URLs for an model object:https://docs.djangoproject.com/en/4.0/ref/models/instances/#get-absolute-url