问:我正在尝试测试用户和帖子的创建以及与每个帖子相关的投票。当我运行时python manage.py tests.py,我得到的错误是'voters' is an invalid keyword argument for this function.
这是我的 models.py 和 tests.py 文件:
模型.py
from django.db import models
from django.contrib.auth.models import User
from datetime import * class Post ( models . Model ): user = models 。ForeignKey ( User , related_name = 'moderated_videos' ) created_at = models 。DateTimeField ( auto_now_add = True )标题=模型。文本字段()
内容 = 模型。TextField ()
点=模型。IntegerField (默认值= 1 )选民=模型。ManyToManyField (用户,related_name = 'liked_posts' )类别=模型。CharField ( max_length = 20 , options = Categories , default = "technology" ) original_poster =
模型。BooleanField (默认= False )
updated_at =模型。DateTimeField ( auto_now = True )
测试.py
from django.test import TestCase
from django.utils import timezone
from django.contrib.auth.models import User from .models import Post class PostTest ( TestCase ): def test_post_creation ( self ): user = User 。对象。create_user ( username = 'shon' ) post = Post 。对象。创建(标题
= "My Title" ,
content = "Some lorem ipsum content" , points = 1 , voters = user , category = "gadgets" , original_poster = False ) now = timezone 。现在()自我。assertLess ( post . created_at , now )
答:正确的。更具体地说,Django 会自动创建一个附加数据库表供您管理ManyToMany关系。需要保存 Post 实例,以便生成 PK。然后可以在 ManyToMany 表中使用此 PK 将 PK 与每个投票者(用户 PK)相关联。