在单个帖子中保存多个模型-Django rest frameweok

时间:2018-08-04 22:04:33

标签: django django-models django-rest-framework

我有4个模型

class User(AbstractEmailUser):
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)

class Event(models.Model):
    name = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    date = models.DateField()

class EventLocation(models.Model):
    event = models.ForeignKey(Event)
    ubigeo = ArrayField(models.CharField(max_length=200), blank=True)

class EventStaff(models.Model):
    recycler = models.ForeignKey(User)
    event = models.ForeignKey(Event)

当我要注册事件并能够在创建时将用户分配给同一出版物时,请分配用户或不分配用户。我已经创建了一个嵌套序列化器,在文档中对此进行了很好的解释,以便保存事件,同时将其保存在EventLocation表的ubigeo字段中(地点):

Class EventLocationSerializer(serializers.ModelSerializer):

    class Meta:
        model = EventLocation
        fields = ('id', 'ubigeo')

class EventSerializer(serializers.ModelSerializer):
event_location = EventLocationSerializer(required=True, write_only=True)

def to_representation(self, instance):
    representation = super(EventSerializer, self).to_representation(instance)
    event_location = EventLocation.objects.filter(event=instance.id)
    if event_location:
        representation['event_location'] = event_location.values('ubigeo')[0]
    return representation

class Meta:
    model = Event
    fields = ('id', 'date', 'name', 'address', 'schedule', 'event_location')

def create(self, validated_data):
    location_data = validated_data.pop('event_location')
    event = Event.objects.create(**validated_data)
    EventLocation.objects.create(event=event, **location_data)
    return event

,它可以正常工作,但是如何将要分配给事件的用户同时添加到事件中?我知道我必须将它们保存在 EventStaff 表中,但是如何将它们插入相同的帖子中?

这是我的视图集

@transaction.atomic
    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            try:  
                data = request.data
                serializer = EventSerializer(data=data)
                if serializer.is_valid(raise_exception=True):
                    serializer.save()
                    return Response({"status": True, "results": "Evento registrado correctamente"},
                                    status=status.HTTP_201_CREATED)
            except ValidationError as err:
                return Response({"status": False, "error_description": err.detail}, status=status.HTTP_400_BAD_REQUEST)

这是json格式:

{
    "date": "2018-03-01",
    "name": "La prueba reciclaje",
    "address": "Av españa trujillo",
    "users": [
        {"id": 40, "first_name": "Raul"},
        {"id": 23, "first_name": "ALejandro"}
    ],
    "eventlocation": {
        "ubigeo": ["130101"]
    }
}

2 个答案:

答案 0 :(得分:0)

我认为,我们可以自定义您的def创建更多内容。 因此,我们为用户创建了一个序列化程序,获取了params用户,并在保存事件后将其保存。 也许像这样:

    <p:dataTable var="categorias" value="#
    {categoriaController.dao.listaCategorias}" selection="#
    {categoriaController.dao.selectedCategoria}" selectionMode="single" 
    rowKey="#{categorias.idCategoria}">
          <p:column headertext"nome da categoria">..............
    </p:datatable/>

获取帮助

答案 1 :(得分:0)

正如我在评论中所说,它的工作效果非常好:D

@transaction.atomic
    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            try:  
                data = request.data
                users = request.data.get('users', None)
                serializer = EventSerializer(data=data)
                if serializer.is_valid(raise_exception=True):
                    instance = serializer.save()
                    if users:
                        for user in users:
                            EventStaff.objects.create(recycler_id=user['id'], event_id=instance.id)
                    return Response({"status": True, "results": "Evento registrado correctamente"},
                                    status=status.HTTP_201_CREATED)
            except ValidationError as err:
                return Response({"status": False, "error_description": err.detail}, status=status.HTTP_400_BAD_REQUEST)