gpt4 book ai didi

python - Django 将模型字段作为参数传递给存储在另一个模型中的 URL

转载 作者:行者123 更新时间:2023-12-01 01:33:01 26 4
gpt4 key购买 nike

我有三个模型:

class Entity(models.Model):
entity = models.CharField(primary_key=True, max_length=25)

class Report(models.Model):
report = models.CharField(max_length=50)
report_link = models.CharField(max_length=300)

class Item(models.Model):
entities = models.ManyToManyField(Entity, related_name='entities')
report = models.ForeginKey(Report)

View 是基于 Item 构建的型号:

def item_list(request):
items = Item.objects.select_related('report').prefetch_related('entities')
return render(request, 'items/item_list.html', {'items':items})

此 View 被路由到模板:

{% for item in items %}
<tr>
<td>
{% for entity in item.entities.all %}
{{ entity }}{% if not forloop.last %}, {% endif %}
{% endfor %}
</td>
<td>{{ item.report }}</td>
<td>{{ item.report.report_link|urlize }}</td>
</tr>
{% endfor %}

此行 ( <td>{{ item.report.report_link|urlize }}</td> ) 在浏览器中的显示如下:

https://server.domain/reports/specificReport?entity=

我如何通过entities进入 URL 来过滤报告?期望的结果如下所示:

https://server.domain/reports/specificReport?entity=12345

...或者如果有多个 entities一个item :

https://server.domain/reports/specificReport?entity=12345,56789

Report 中的每份报告模型有一个链接,但该链接不一定采用实体参数,因此全局更改所有链接(即通过 jQuery 或其他 JS)并不理想。然而,这个页面上运行着 JS,所以可以使用它......尽管我认为 Django 选项可能是最好的。

我考虑过的一件事是向 Report 添加一个指示器标记是否 entities 的模型应该添加到链接中...但这并不能解决将一个模型字段附加到另一个模型字段的末尾并将它们一起“url化”的主要问题。

最佳答案

model method怎么样?创建链接? Django 文档提到了以下有关使用模型方法的内容,这适用于您的用例

This is a valuable technique for keeping business logic in one place – the model.

这意味着您不需要深入研究模板和模板标签来查看项目的报告链接是如何生成的 - 您可以在 models.py 中查看所有内容

以下内容可能是一个起点

class Item(models.Model):
entities = models.ManyToManyField(Entity, related_name='entities')
report = models.ForeginKey(Report)

def get_report_link(self):
link_text = self.report.report_link
if self.entities.count() > 0:
link_text + "?entity={}".format(','.join([entity.id for entity in self.entities.all()]))
return link_text

然后在模板中:将 item.report.report_link|urlize 更改为 item.get_report_link

关于python - Django 将模型字段作为参数传递给存储在另一个模型中的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52651205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com