如何过滤外键字段编辑的值?

时间:2017-12-13 14:56:48

标签: django django-models django-forms django-admin

我有三个简单的模型:

class Task(models.Model):
    code = models.CharField(max_length=200, unique=True)
    tags = models.ManyToManyField(Tag, blank=True)

class Session(models.Model):
    tasks = models.ManyToManyField(Task, through='TaskInSession')

class TaskInSession(models.Model):
    session = models.ForeignKey(Session, on_delete=models.CASCADE)
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    count = models.IntegerField()

对于会话编辑,我有:

class SessionAdmin(admin.ModelAdmin):
    inlines = [TaskInSessionInline,]
    exclude = ('tasks', )

是否可以通过标签可能性添加任务过滤,以便在会话编辑时轻松选择任务?

1 个答案:

答案 0 :(得分:0)

你应该在models.py中定义你的Tag类。也许是这样的:

class Tag(models.Model):
  Name = models.CharField(max_length=200, unique=True)

然后在您的views.py中获得所需的标记。例如:

desired_tag = Tag.objects.get(Name='some_name') # you could as well get the desired tagby the pk attribute.  

最后,获取与该标记关联的所有任务。例如:

filtered_tasks = Tasks.objects.filter(tags=desired_tag)

您正在查找的查询将是filtered_tasks。