Home > Mobile >  'QuerySet' object has no attribute '_meta', Django with ajax
'QuerySet' object has no attribute '_meta', Django with ajax

Time:05-05

I am building a site for a tattoo shop. In my index view I first display all tattoos by every artist but I am trying to allow users to filter tattoos by artist and then update the page displaying tattoos by the selected artist using jquery/ajax.

Artist and Tattoo models:

class Artist(models.Model):
    first_name  = models.CharField(max_length=50)
    last_name  = models.CharField(max_length=50)
    # etc

class Tattoo(models.Model):
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    name  = models.CharField(max_length=150)
    image = models.ImageField(upload_to='images/')
    date_created = models.DateTimeField(auto_now_add=True)

forms.py:

class FilterArtForm(ModelForm):
    class Meta:
        model = Tattoo
        fields = ['artist']

        widgets = {
            'artist': forms.Select(attrs={'id': 'filter_by_artist'}),
        }

views.py:

def index(request):
    tattoos = Tattoo.objects.order_by('-date_created')
    filter_art_form = FilterArtForm()
    artist_id = request.GET.get('artist')
    if artist_id:
        artist = Artist.objects.get(pk = artist_id)
        tattoos = tattoos.filter(artist=artist) # trying to return this as a JsonResponse is causing some kind of issue
        return JsonResponse({'tattoos': model_to_dict(tattoos)}, status=200)
    return render(request, 'core/index.html', {'tattoos':tattoos, 'filter_art_form': filter_art_form})

I am new to working with ajax so I was just messing around with my view and if I try to return only the Artist object as such:

 def index(request):
        tattoos = Tattoo.objects.order_by('-date_created')
        filter_art_form = FilterArtForm()
        artist_id = request.GET.get('artist')
        if artist_id:
            artist = Artist.objects.get(pk = artist_id)
            return JsonResponse({'artist': model_to_dict(artist)}, status=200)
        return render(request, 'core/index.html', {'tattoos':tattoos, 'filter_art_form': filter_art_form})

this will work and I will get the following response:

{"artist": {"id": 1, "first_name": "First", "last_name": "Last"}}

But when I try and retrieve the Tattoo objects associated with said Artist I get this 'QuerySet' object has no attribute '_meta' error. I am thinking it is has to do with ImageField of the Tattoo model or with the fact that this is returning multiple objects instead of just one single object, but I am not sure. Thanks for any help with this.

CodePudding user response:

Try like this

if artist_id:
   tattoos = tattoos.filter(artist__id=artist_id).values()
   return JsonResponse({'tattoos_by_artist': list(tattoos)}, status=200)
  • Related