我正在使用SwampDragon创建聊天演示,我不确定如何创建包含相关字段的模型。
使用下面的代码,每次在javascript中调用createMessage
函数时都会发生错误。我收到的唯一错误来自websocket输出:c[3001,"Connection aborted"]
。在python控制台上有 no 输出,可以解决这个错误。
任何人都可以帮助我了解如何使用Message
的相关字段创建User
吗?
from django.contrib.auth.models import User
from django.db import models
from swampdragon.models import SelfPublishModel
from .serializers import MessageSerializer
class Message(SelfPublishModel, models.Model):
serializer_class = MessageSerializer
user = models.ForeignKey(User, related_name='messages')
body = models.TextField(blank=True)
from swampdragon.serializers.model_serializer import ModelSerializer
from django.contrib.auth.models import User
class UserSerializer(ModelSerializer):
class Meta:
model = User
publish_fields = ('id', 'username')
update_fields = ('first_name', 'last_name', )
class MessageSerializer(ModelSerializer):
user = UserSerializer
class Meta:
model = b'chat.Message'
publish_fields = ('body', 'user', )
update_fields = ('body', 'user', )
from swampdragon import route_handler
from swampdragon.route_handler import ModelRouter, BaseRouter
from .models import Message
from .serializers import MessageSerializer, UserSerializer
class MessageRouter(ModelRouter):
route_name = 'message'
serializer_class = MessageSerializer
model = Message
include_related = [UserSerializer, ]
def get_object(self, **kwargs):
return self.model.objects.get(pk=kwargs['id'])
def get_query_set(self, **kwargs):
return self.model.objects.all()
route_handler.register(MessageRouter)
...
createMessage: function(message){
var data = {
user: 1,
body: message
};
swampdragon.create('message', data, function (context, data) {
console.log('MessageStore: onCreate success.', context, data);
}, function (context, data) {
console.log('MessageStore: onCreate failed.', context, data);
});
},
...
答案 0 :(得分:1)
回答我自己的问题:这不像我预期的那样内置于框架中。您需要使用get_initial
方法在路由器中实例化相关模型。然后将这些传递给序列化程序并正确创建Message
模型。
class MessageRouter(ModelRouter):
route_name = 'message'
serializer_class = MessageSerializer
model = Message
include_related = [UserSerializer, ]
def get_initial(self, verb, **kwargs):
user = User.objects.get(pk=kwargs['user_id'])
return {'user': user}
def get_object(self, **kwargs):
return self.model.objects.get(pk=kwargs['id'])
def get_query_set(self, **kwargs):
return self.model.objects.all()
...
createMessage: function(message){
var data = {
user_id: 1,
body: message
};
swampdragon.create('message', data, function (context, data) {
console.log('MessageStore: onCreate success.', context, data);
}, function (context, data) {
console.log('MessageStore: onCreate failed.', context, data);
});
},
...
class MessageSerializer(ModelSerializer):
user = UserSerializer
class Meta:
model = b'chat.Message'
publish_fields = ('body', 'user', )
update_fields = ('body', )