DRF Serializer外键反向查找

时间:2018-06-12 22:10:11

标签: django django-rest-framework

我正在尝试发送以下HTTP Post API请求以创建新的INSERT OR REPLACE INTO output_to_cloud3 VALUES ('U','V','W','X'), -- New non-duplicate row ('A','B','C','D'), ('E','F','G','H'), ('I','J','K','L'), ('M','N','O','P'), ('Z','AA','AB','AC'), -- New non-duplicate row ('Q','R','S','T'), ('AD','AE','AF','AG') -- New non-dupliate row ; 对象。如何在最小的有效载荷中完成此操作而不是发送整个对象?我正在尝试额外的一层安全混淆,而不是使用默认的整数EventInterest,我如何使用pk uuidEventusername 1}? ....或者额外的SQL查找否定了简化有效负载的好处,我应该使用User

models.py

pk

api.py

class Event(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(max_length=500)
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, db_index=True, blank=True)

class EventInterest(models.Model):
    event = models.ForeignKey(Event)
    sender = models.ForeignKey(settings.AUTH_USER_MODEL)  # from User

serializer.py

class EventInterestViewSet(mixins.CreateModelMixin, GenericViewSet):

    queryset = models.EventInterest.objects.all()
    serializer_class = serializers.EventInterestSerializer
    lookup_field = 'uuid'

HTTP Post:

class EventInterestSerializer(serializers.ModelSerializer):
    # event = serializers.SlugRelatedField(read_only=True, slug_field='uuid')
    # recipient = serializers.SlugRelatedField(read_only=True, slug_field='username')
    # sender = serializers.SlugRelatedField(read_only=True, slug_field='username')

    class Meta:
        model = models.EventInterest
        fields = (
            'event',  #works with pk, want uuid
            'sender',  # works with pk, want username
        )

2 个答案:

答案 0 :(得分:1)

您需要将UUIDField作为主键。就像这样:

class Event(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
    ....

答案 1 :(得分:1)

uuid模型中定义Event时,您还必须在uuid模型中定义User。为此,您必须扩展默认用户模型。然后,您必须覆盖create() EventInterestSerializer方法,以便在相应的UUID字段上进行查找而不是pk

models.py

from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, db_index=True)


class Event(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(max_length=500)
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, db_index=True)


class EventInterest(models.Model):
    event = models.ForeignKey(Event)
    sender = models.ForeignKey(User)


serializer.py

class EventInterestSerializer(serializers.ModelSerializer):
    class Meta:
        model = EventInterest
        fields = ('event', 'sender',)

    def create(self, validated_data):
        try:
            return EventInterest.objects.get(event__uuid=validated_data['event'],
                                             sender__uuid=validated_data['sender'])
        except EventInterest.DoesNotExist:
            raise serializers.ValidationError("No matching data found")