多对多字段不返回django

时间:2018-07-21 03:58:27

标签: python django django-models many-to-many models

当我尝试在终端中打印一个字段(多对多)时,我只会得到结果“无”。我想念什么吗?

view.py

def assign_skill (request, pk):
    plan = get_object_or_404(Plan, pk=pk)

    if(request.GET.get('assign_skill')):
        print("nummer1")
        print(plan.title)
        print(plan.skillonplan)
    return redirect('all-plan')

models.py

class Plan(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False)
    subscriber = models.ManyToManyField(User, blank = True, related_name = 'plansubscriber')
    title = models.CharField(max_length=100, default = '', null=True, blank=True)
    description = models.TextField(max_length=10000, default = '', null=True, blank=True)
    company = models.CharField(max_length=200, null=True, editable=False)
    created_date = models.DateTimeField(default=timezone.now)
    skillonplan = models.ManyToManyField(Skill, null=True, blank = True, related_name='planneke')
    duration = models.IntegerField(default=0,
    validators=[MaxValueValidator(36), MinValueValidator(1)]
    )

    def get_skills(self):
        return '\n'.join([p.skills for p in self.skill.all()])


    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse_lazy('plan_detail', kwargs={'pk': self.id})

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码,以返回许多字段:

print(plan.skillonplan.all())