CarinaTheBookworm
CarinaTheBookworm

Reputation: 195

Django TypeError object of type 'ManyRelatedManager' has no len()

I am trying to customise the create method for Combination objects. The field tag_id should be limited to 2 Tag instances. I have tried something like

if len(combination.tag_id) == 2:

and I am getting the error object of type 'ManyRelatedManager' has no len()

Is there another way to set the maximum length of this field to 2?

models.py

class Combination(models.Model):

    user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
    tag_id = models.ManyToManyField(Tag, null=True)
    created = models.DateTimeField(editable=False)
    score = models.PositiveIntegerField(default=0)

    objects = models.Manager()

    def __str__(self):
        return str(self.tag_id) or ''

serializers.py

  def create(self, validated_data):
    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0
    resource_id = validated_data.get("resource")

    combination = Combination(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      created=datetime.now(),
      score=score
    )
    combination.save()

    tag_data = validated_data.pop('tag_id', None)
    for tag_item in tag_data:
      tag = Tag.objects.get_or_create(**tag_item)[0]
      combination.tag_id.add(tag)

      # if len(combination.tag_id) == 2:
    return combination

Upvotes: 2

Views: 1390

Answers (1)

CarinaTheBookworm
CarinaTheBookworm

Reputation: 195

Solved by adding:

      if combination.tag_id.count() == 2:
        return combination

Upvotes: 3

Related Questions