简体   繁体   中英

Discard records using serializers of Django rest framework

I need to discard all records that have no associated images. This must be implemented in serializers.

If there is a solution in the views, it is also welcome.

I have these models

class Activity(models.Model):
  """ Class Activity """
  name = models.CharField(max_length = 200, null = False, blank = False)
  create_at = models.DateTimeField('Create date', auto_now_add = True, editable = False)
  update_at = models.DateTimeField('Last update', auto_now = True)

class Image(models.Model):
  """ Image of an activity """
  activity = models.ForeignKey(Activity, related_name = 'images', on_delete = models.CASCADE)
  image = models.ImageField(upload_to = 'files/images')

And following serializers

class ImageModelSerializer(serializers.ModelSerializer):
  """ Image model serializer """
  class Meta:
    model = Image
    fields = ('id', 'image')

class ActivityModelSerializer(serializers.ModelSerializer):
  """ Activity model serializer """
  images = ImageModelSerializer(read_only = True, many = True)
  class Meta:
    model = Activity
    fields = ('id', 'name', 'images', 'create_at')

Here are examples of the response I need to get.

Example:

  1. Correct
[
{
  "id": 1,
  "name": "Activity 1",
  "images": [
    {"id": 1, "image": "path to image 1"},
    {"id": 2, "image": "path to image 2"}
  ],
  "create_at": "2021-04-07T15:58:15.409054Z"
},
{
  "id": 3,
  "name": "Activity 3",
  "images": [
    {"id": 3, "image": "path to image 1"},
    {"id": 4, "image": "path to image 2"}
  ],
  "create_at": "2021-04-07T15:58:15.409054Z"
}
]
  1. Incorrect
[
{
  "id": 1,
  "name": "Activity 1",
  "images": [
    {"id": 1, "image": "path to image 1"},
    {"id": 2, "image": "path to image 2"}
  ],
  "create_at": "2021-04-07T15:58:15.409054Z"
},
{
  "id": 2,
  "name": "Activity 2",
  "images": [],
  "create_at": "2021-04-07T15:58:15.409054Z"
},
{
  "id": 3,
  "name": "Activity 3",
  "images": [
    {"id": 3, "image": "path to image 1"},
    {"id": 4, "image": "path to image 2"}
  ],
  "create_at": "2021-04-07T15:58:15.409054Z"
}
]

Thanks and hor that you can help me!

You would need to overwrite the queryset in the API view:

class ActivityModelSerializerViewSet(viewsets.ModelViewSet):
    queryset = Activity.objects.filter(add_filtering_rules_here)
    serializer_class = ActivityModelSerializer

Also, you would need to check how the image field is represented in the database in order to set the proper filter. Probably this(or similar) should work but you have to test it first:

Activity.objects.filter(images__image__isnull=False)
Activity.objects.exclude(images__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