django为内容类型模型管理模型

时间:2016-10-13 04:38:09

标签: python django django-models django-testing

我目前正在编写一个包含所有内容类型模型(通用关系)的Django应用程序

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core.validators import RegexValidator

class AddressManager(models.Manager) :
    def create_address(self, content_obj, address1, address2, postal_code):
        address = Address(content_object = content_obj,
                          address1 = address1,
                          address2 = address2,
                          postal_code = postal_code)
        address.save()
        return address

class Address(models.Model):
    address1 = models.CharField(max_length=100, default=None)
    address2 = models.CharField(max_length=100, default=None)
    postal_code = models.TextField(default=None)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,
                                     default=None, null=True)
    object_id = models.PositiveIntegerField(default=None, null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    objects = AddressManager()

当我在本地服务器上使用它时,它很有用。

然而,当我跑

python manage.py test

发生此错误

======================================================================
ERROR: test_address__custom_methods (genericmodels.tests.test_models.TestBasic)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/genericmodels/tests/test_models.py", line 15, in test_address__custom_methods
    "t_postal_code")
  File "/path/genericmodels/models.py", line 11, in create_address
    postal_code = postal_code)
  File "/path/env3/lib/python3.5/site-packages/django/db/models/base.py", line 555, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'content_object' is an invalid keyword argument for this function

----------------------------------------------------------------------
Ran 1 test in 0.310s

FAILED (errors=1)
Destroying test database for alias 'default'...

测试代码如下:

from django.test import TestCase
from unittest.mock import MagicMock

from genericmodels.models import *
from anotherapp.models import User_Info


class TestBasic(TestCase):
    """ Basic tests for Address model"""
    def test_address__custom_methods(self):
        user_info = MagicMock(User_Info)
        address = Address.objects.create_address(user_info,
                                                 "t_address1",
                                                 "t_address2",
                                                 "t_postal_code")
        self.assertEqual(Address.objects.count(), 1)
        self.assertEqual(address.address1, "t_address1")

1 个答案:

答案 0 :(得分:0)

感谢TickTomp我能够弄清楚,而不是制作一个MagicMock(User_Info),我应该实际上做了一个User_Info类的实例来测试。之后测试运行良好......