合并模型以获得连贯的数据

huangapple go评论61阅读模式
英文:

Combine models to get cohesive data

问题

"我正在编写一个应用程序,其中我将数据存储在不同的模型中。现在我需要将这些数据组合起来以便使用它。

问题

我有三个模型:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=50, blank=True)
    ...

class Contacts(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user")
    contact_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="contact_user")

class UserPhoto(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    url = models.CharField(max_length=220)

我该如何获取当前用户的联系人,包括他们的姓名和图片,就像这样(序列化):

{
 {
   "contact_user":"1",
   "first_name":"Mark",
   "url":与contact_user id相对应的第一张图片
 },
 {
   "contact_user":"2",
   "first_name":"The Rock",
   "url":与contact_user id相对应的第一张图片
 }
}

现在,我正在查询Contacts模型,以获取他与之有联系的所有contact_user id。

class MatchesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Contacts
        fields = '__all__'
        depth = 1

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactsSerializer
    
    def get_queryset(self):
        return Contacts.objects.filter(user__id=self.request.user.id)

"

英文:

I'm writing app in witch I store data in separate models. Now I need to combine this data to use it.

The problem

I have three models:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=50, blank=True)
    ...

class Contacts(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user")
    contact_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="contact_user")

class UserPhoto(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    url = models.CharField(max_length=220)

How can I get the current user contacts with their names and pictures like this (serialized)

{
 {
   "contact_user":"1",
   "first_name":"Mark ",
   "url":first picture that corresponds to contact_user id
 },
 {
   "contact_user":"2",
   "first_name":"The Rock",
   "url":first picture that corresponds to contact_user id
 }
}

Now I'm querying the Contacts model to get all contacts_user id's that he has connection to.

class MatchesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Contacts
        fields = '__all__'
        depth = 1

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactsSerializer
    
    def get_queryset(self):
        return Contacts.objects.filter(user__id=self.request.user.id)

答案1

得分: 1

需要做的事情是将Contacts查询集序列化,以包括每个联系人的相关UserUserPhoto对象。

尝试为Contacts模型创建自定义序列化器,如下所示:

class ContactSerializer(serializers.ModelSerializer):
    contact_user = serializers.SerializerMethodField()

    def get_contact_user(self, obj):
        user = obj.contact_user
        photo = user.userphoto_set.first()
        return {
            "id": user.id,
            "first_name": user.first_name,
            "url": photo.url if photo else None
        }

    class Meta:
        model = Contacts
        fields = ("contact_user",)

然后,修改ContactViewSet以使用这个新创建的序列化器,如下所示:

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactSerializer

    def get_queryset(self):
        return Contacts.objects.filter(user__id=self.request.user.id)

注意: 一般来说,Django模型不需要添加s作为后缀,因为它默认会自动添加,所以最好将其从Contacts改为Contact

英文:

The thing you need to is to serialize the Contacts queryset to include the related User and UserPhoto objects for each contact.

Try to create a custom serializer for the Contacts model so:

class ContactSerializer(serializers.ModelSerializer):
    contact_user = serializers.SerializerMethodField()

    def get_contact_user(self, obj):
        user = obj.contact_user
        photo = user.userphoto_set.first()
        return {
            "id": user.id,
            "first_name": user.first_name,
            "url": photo.url if photo else None
        }

    class Meta:
        model = Contacts
        fields = ("contact_user",)

Then, modify the ContactViewSet to use this newly created serializer so:

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactSerializer
    
    def get_queryset(self):
        return Contacts.objects.filter(user__id=self.request.user.id)

> Note: Generally, Django models don't require s to be added as suffix since it is by default added, so it is better to modify it as Contact from Contacts.

huangapple
  • 本文由 发表于 2023年2月19日 22:42:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定