Django- 我如何获取与另一个模型相关的模型的内容?

所以我正在创建一个待办事项应用程序。如何查看链接到版块的任务?就像我理解的那样,董事会需要成为任务的外键。


这是我到目前为止的代码:Models.py


class Board(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board")

name = models.CharField(max_length=200)


class Task(models.Model):

    board = models.ForeignKey(Board, on_delete=models.CASCADE)

    admin = models.ForeignKey(User, on_delete=models.CASCADE)

    text = models.CharField(max_length=300)

    complete = models.BooleanField(default=False)

    assigned_to = models.CharField(max_length=30)

views.py


def board_post_detail(request, board_id):

obj = get_object_or_404(Board, id=board_id)

context = {"object": obj}


return render(request, 'boards/board_post_detail.html', context)

board_post_detail.html


{% block content %}

<h1>{{ object.name}}</h1>

<p>Created by {{object.admin.username  }}</p>

{% endblock %}


梵蒂冈之花
浏览 88回答 1
1回答

holdtom

如果要查找与 Board 类的特定实例对应的任务,则只需按实例进行查询筛选:obj&nbsp;=&nbsp;get_object_or_404(Board,&nbsp;id=board_id) Task.objects.filter(board=obj)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python