0

Trying to create a column in my model called, stock_count, that finds the sum of the total string objects in my ArrayField(), aka stock_list. Here is my function.

    def total_stocks_calc(self):
        self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True))
        self.save()

However it doesn't seem to be doing anything, no calculating, leaving the field blank in my model, admin page, and DRF interface...

EDIT: updated post with new implementation.

Here is my model.

class Bucket(models.Model):


    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets')
    users = models.ManyToManyField(settings.AUTH_USER_MODEL)
    category = models.CharField(max_length=30, choices=category_options)
    name = models.CharField(max_length=35)
    created = models.DateTimeField(default=timezone.now)
    slug = models.SlugField(unique=True, blank=True) 
    stock_count = models.IntegerField(blank=True, null=True)
    stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True)
    about = models.CharField(max_length=75)

    objects = models.Manager()
    bucketobjects = BucketObjects()

    class Meta:
        ordering = ('-created',)

    def total_stocks_calc(self):
        self.stock_count = Bucket.objects.annotate(stock_count=F('stock_list__len'))
        self.save()


    def __unicode__(self):
        return self.stock_list

Would like to know the proper way to count total items in ArrayField(), thank you in advance.

1 Answer 1

1

The ArrayField provides the len lookup field, through that you can get the count

like

from django.db.models import F    
Bucket.objects.annotate(stock_count=F('stock_list__len'))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your comment, I tested out your snippet, I'm trying to get it to work though, and I'm not able to get it to start counting how many items are in the ArrayField. I added a new edit to the OG post to show you how I implemented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.