Ich bin derzeit eine Django-Anwendung zu schreiben, alle Content Type Modelle enthalten (generische Beziehungen)django Modelle Manager für Content-Type Modelle
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()
Wenn ich diese auf lokalen Server, es seinen Zweck gut dient.
Allerdings, wenn ich
Python manage.py Test
Dieser Fehler
======================================================================
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'...
Der Testcode ist wie folgt auftritt laufen:
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")
Das content_object ist GenericForeignKey, also müssen Sie die Instanzen an das content_object übergeben. anstatt Benutzerinfo direkt zu übergeben –
Danke, du hattest Recht !! @TickTomp –