from pathlib import Path
from django.core.management.base import BaseCommand
from django.conf import settings

from petition.models import Petition



class Command(BaseCommand):
    """find orphans medias in mediaroot
    """
    def handle(self, *args, **options):
        mediaroot = Path(settings.MEDIA_ROOT)
        all_petition = Petition.objects.all()
        last_petition = all_petition[len(all_petition)-1]
        for media in mediaroot.glob('**/*.*'):
            media = str(media)
            for petition in all_petition:
                if media in petition.text or media in petition.twitter_image:
                    break
                if petition == last_petition:
                    print(media)

@@ -3,14 +3,22 @@
 om p
-athlib
+etition.models
  imp
@@ -22,19 +22,23 @@
 import P
-ath
+etition
 %0Afrom dj
@@ -119,29 +119,20 @@
 ngs%0A
-%0A
 from p
-etition.models
+athlib
  imp
@@ -136,24 +136,19 @@
 import P
-etition%0A
+ath
 %0A%0A%0Aclass
@@ -327,16 +327,21 @@
 ition = 
+list(
 Petition
@@ -354,16 +354,17 @@
 ts.all()
+)
 %0A       
@@ -364,20 +364,22 @@
         
-last
+if all
 _petitio
@@ -383,14 +383,26 @@
 tion
- = all
+:%0A            last
 _pet
@@ -410,13 +410,11 @@
 tion
-%5Blen(
+ = 
 all_
@@ -425,13 +425,14 @@
 tion
-)
+%5B
 -1%5D%0A
+%0A
     
@@ -505,16 +505,49 @@
 (media)%0A
+            if all_petition:%0A    
         
@@ -596,16 +596,20 @@
         
+    
 if media
@@ -682,16 +682,20 @@
         
+    
 break%0A  
@@ -708,16 +708,20 @@
         
+  
+  
 if petit
@@ -762,16 +762,20 @@
         
+    
 print(me
@@ -771,16 +771,76 @@
    print(media)%0A
+            else:%0A                print(media)%0A            %0A

convert queryset to list