从其他应用程序导入urls.py中的一个模型

时间:2015-06-04 08:54:42

标签: python django django-models

我正在尝试从不同的应用程序中的urls.py中的另一个应用程序导入模型。

这是我的代码

主要/ settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'clients',
    'rest_framework',
)

主要/ urls.py

from django.conf.urls import url, include
from django.contrib import admin

from django.contrib.auth.models import User, Group

from rest_framework import serializers
from rest_framework import viewsets
from rest_framework import routers

from myapp.clients.models import Client

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

class ClientViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Client.objects.all()
    serializer_class = UserSerializer


router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
router.register(r'clients', ClientViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include('rest_framework.urls', namespace='rest_framework'))
]

客户端/ models.py

from django.db import models

class Client(models.Model):
    phone_number = models.CharField(max_length=20)
    name = models.CharField(max_length=50)
    occupation = models.CharField(max_length=100)
    status = models.IntegerField(default=1)
    number_of_requests = models.IntegerField(default=0)
    karma = models.IntegerField(default=5)
    member_from = models.DateTimeField('member from')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

我收到错误没有名为'myapp.clients'的模块

main / urls.py in,第25行

就是这一行:来自myapp.clients.models导入客户端的

有人可以建议我该如何解决这个问题?我是python的新手,并且在这个问题上挣扎了好几个小时。谢谢!

1 个答案:

答案 0 :(得分:3)

clients是已安装的应用,因此您应该可以将该行更改为:

from clients.models import Client