я в настоящее время пишущие приложения Django, чтобы содержать все Content Type Модели (общие отношения)Джанго модели менеджер для моделей контента типа
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()
Когда я использую это на локальном сервере, он служит своей цели хорошо.
Однако, когда я бегу
тест питон manage.py
Эта ошибка возникает
======================================================================
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")
content_object - это GenericForeignKey, поэтому вам нужно передать экземпляры в content_object. вместо того, чтобы передавать userinfo напрямую –
Спасибо, вы были правы! @TickTomp –