django 从 shell 中的一对多模型关系中检索所有对象
django retrieving all objects from one to many model relationship in shell
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Board(models.Model):
title = models.CharField(max_length=50, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Task(models.Model):
title = models.CharField(max_length=200, null=True)
done = models.BooleanField(default=False, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
如何获取一个面板中的所有任务? (每个用户都可以创建一个板,用户可以在该板内创建任务)我试过 Board.objects.get(pk=1).title.title
但这似乎不起作用。
您可以检索Board
对象,然后用task_set
查询:
board = Board.objects.get(pk=1)
board<b>.task_set.all()</b> # queryset of <i>related</i> Tasks
如果您对 Board
本身不感兴趣,您可以省略查询 Board
,并使用以下内容进行过滤:
Task.objects.filter(<b>board_id=1</b>) # queryset of <i>related</i> Tasks
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Board(models.Model):
title = models.CharField(max_length=50, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Task(models.Model):
title = models.CharField(max_length=200, null=True)
done = models.BooleanField(default=False, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
如何获取一个面板中的所有任务? (每个用户都可以创建一个板,用户可以在该板内创建任务)我试过 Board.objects.get(pk=1).title.title
但这似乎不起作用。
您可以检索Board
对象,然后用task_set
查询:
board = Board.objects.get(pk=1)
board<b>.task_set.all()</b> # queryset of <i>related</i> Tasks
如果您对 Board
本身不感兴趣,您可以省略查询 Board
,并使用以下内容进行过滤:
Task.objects.filter(<b>board_id=1</b>) # queryset of <i>related</i> Tasks