简体   繁体   中英

Use uuid as foreign Key in a model in Django with Django Rest Framework

I don't know if the title of the post is right. I'll explain what I want to do and you could tell me what's the best way.

I want to have an "id" (Int) as Primary Key and a "uuid" (uuid) as field in my User model. So, I want to link the tables with the "id", because it's faster, but I want that the front end just see the "uuid" and never the "id", because is a bit safer.

My problem is that I've a "message" model. It looks so:

class Message(models.Model):
    created = models.DateTimeField(auto_now_add=True)

    type = models.CharField(_('type'), choices=MESSAGE_TYPE, default='Invitation', max_length=100)
    content = models.TextField(_('content'), blank=False)
    sender = models.ForeignKey(User, related_name='sender_message', verbose_name=_("Sender"), )
    recipient = models.ForeignKey(User, related_name='receiver_message', null=True, blank=True,
                                  verbose_name=_("Recipient"))
    url_profile_image = models.URLField(_('url_profile_image'), max_length=500, blank=True, default='')

    class Meta:
        ordering = ('created',)

And as you can see, "sender" and "recipient" are linked to my User with a ForeignKey . But that ForeignKey returns as the user Id.

  {
    "url": "http://127.0.0.1:8000/users/messages/4/",
    "id": 4,
    "type": "invitation_accepted",
    "content": "Sure",
    "sender": 4,
    "recipient": 1,
    "url_profile_image": ""
  }

4 is the id of the "sender" and 1 is the id of the "recipient". But I would like that the front end just see the "uuid" of the sender and the "uuid" of the recipient.

My serializer looks so:

class MessageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Message
        fields = ('url', 'id', 'type', 'content', 'sender', 'recipient', 'url_profile_image')

So, I thought that maybe there're two ways to do what I want.

Either use the uuid as Foreign Key or do something in the serializer and get the uuid of the user and return it in "sender" and "recipient".

My view is quite simple:

class MessageViewSet(viewsets.ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer

(don't worry about the queryset, it looks crazy, but it's so :) that kind of message is not private :D )

Maybe someone can help me.

You can try

class MessageSerializer(serializers.ModelSerializer): 
    sender = serializers.ReadOnlyField(source='sender.uid')
    recipient = serializers.ReadOnlyField(source='recipient.uid')

    class Meta: 
        model = Message 
        fields = ('url', 'id', 'type', 'content', 'sender', 'recipient', 'url_profile_image')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM