用户对象在ManytoMany中返回None

时间:2016-01-27 18:08:33

标签: python django

User对象和Movement对象之间有很多关系。每次我运行测试以查看User对象是否已成功添加,我都会获得auth.User.None

型号:

class Movement(models.Model):
    zipcode = models.ForeignKey('ZipCode')
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=400, null=False, 
        blank=True)
    users = models.ManyToManyField(User)
    slug = models.SlugField(unique=True)


    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Movement, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

形式:

class MovementForm(forms.ModelForm):  

    title= forms.CharField(max_length=100, help_text="Movement title")
    description = forms.CharField(help_text="Movement description",
        widget=forms.Textarea(attrs={'paceholder':'Please enter your description'}))
    slug = forms.CharField(widget=forms.HiddenInput(), required=False)

    class Meta:
        model = Movement
        exclude = ['zipcode', 'users']

查看:

@login_required
def new_movement(request):
    template = 'new_movement.html'


    if request.method == 'POST':
        zipcode_form = ZipCodeForm(data=request.POST)
        movement_form = MovementForm(data=request.POST)

        if zipcode_form.is_valid() and movement_form.is_valid():
            zipcode, create = ZipCode.objects.get_or_create(**zipcode_form.cleaned_data)
            movement = movement_form.save(commit=False)
            movement.zipcode = zipcode
            movement.save()
            movement.users.add(request.user)
            movement.save()
            return redirect('/%s/results' %zipcode.zipcode)
    else:

        zipcode_form = ZipCodeForm()
        movement_form = MovementForm()

    return render(request, template, 
        {'movement_form':movement_form, 'zipcode_form':zipcode_form})

    return render(request, template, {} )

一切运行正常,但是当我运行我的测试代码希望得到用户的名字时,我得到的只是auth.User.None。

test.py:

class NewMovementViewTest(TestCase):

    def setUp(self):
        self.user = User.objects.create_user(
            username='Megan',
            email='megan@email.com',
            password='password',
        )
        self.client.login(username='Megan', password='password')

    def test_new_movement_saves_user(self):

        response = self.client.post('/new_movement/',
            data={'title':'A movement',
            'zipcode':20016,
            'description':'Some movement'})
        movements = Movement.objects.all()
        self.assertEqual(movements.count(), 1)
        movement= movements[0]
        self.assertEqual(movement.title, 'A movement')
        self.assertEqual(movement.zipcode.zipcode, 20016)
        self.assertEqual(movement.description, 'Some movement')
        users = Movement.objects.filter(users__username__startswith="Megan")
        print(users[0].users)

测试输出:

Creating test database for alias 'default'...
auth.User.None
.
----------------------------------------------------------------------
Ran 1 test in 0.191s

OK

1 个答案:

答案 0 :(得分:0)

        users = Movement.objects.filter(users__username__startswith="Megan")

只是关于命名的注释 - 这将返回'运动'查询集 - 而不是任何用户信息。它基于过滤器返回移动对象(在这种情况下,过滤关系);但请注意它们是Movement对象,而不是User对象。

您可以使用索引来获取第一个Movement对象 - 但users[0].users将返回一个对象管理器(特别是'ManyRelatedManager')。如果要检查与此对象关联的用户,可以将其视为大多数其他对象管理器,并执行以下操作:

user = users[0].users.first()

all_users = users[0].users.all()

随意参考Django指南 - 它在多对多关系中有一些很好的例子。 https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/