I have 2 models but I want to show the name of the artist in my output
class Musician(models.Model):
name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
name = models.CharField(max_length=100)
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
num_stars = models.IntegerField()
I want to show musician name by HttpResponse function
class Musician_list(Musician, Album):
def get(self, request):
query = Musician.objects.all().values_list("name").order_by("name")
return HttpResponse(query)
but this code doesn't show anything - please help me.
from django.http import JsonResponse
def get(self, request):
names = Musician.objects.values_list("name",flat=True)
return JsonResponse(names, safe=False)
You can read more about JsonResponse from the doc here
Your Usecase
Related
i'm trying to use django generic view. and i want to be able to delete multiple objects at the same time using the same view.for example delete all the 'femail' Employees in my model.
i used the following code:
from ..models import Employee
from . import serializer
from rest_framework import generics, status
from rest_framework.response import Response
from django.shortcuts import get_list_or_404, get_object_or_404
class EmployeeDeleteandUpdate(generics.UpdateAPIView):
queryset = Employee.objects.filter(gender__startswith='femail')
serializer_class = serializer.PostSerializer
def delete(self, request, *args, **kwargs):
myobj = get_object_or_404(Employee, gender=kwargs['gender'])
myobj.delete()
return Response("Femails deleted", status=status.HTTP_204_NO_CONTENT)
and heres my url code:
path('mydel/<str:gender>/', view.EmployeeDeleteandUpdate.as_view()),
and also my model:
class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
gender = models.CharField(max_length=10)
national_code = models.CharField(max_length=11)
personal_code = models.CharField(max_length=15)
phone_number = models.CharField(max_length=11)
address = models.CharField(max_length=50)
married = models.BooleanField()
age = models.IntegerField()
wage = models.IntegerField()
def __str__(self):
return self.first_name
but when i use delete method with following url in my django rest framework:
http://127.0.0.1:8000/mydel/femail/
i get this error:
client.models.Employee.MultipleObjectsReturned: get() returned more
than one Employee -- it returned 2!
can somebody help me with this problem please??
The get_object_or_404 method only gets 1 object from the table so it is compulsory the record will be unique in the table. Otherwise, it gives an error.
Please try this code:
def delete(self, request, *args, **kwargs):
employees = Employee.objects.filter(gender=kwargs['gender'])
if employees.count() > 0:
employees.delete()
return Response("Femails deleted", status=status.HTTP_204_NO_CONTENT)
return Response("Unable to find the femails.", status=status.HTTP_404_OK)
In this code snippet, I am filtering the result based on kwargs['gender'] and then count its objects if greater than one then delete it using the loop.
I am new to back-end programming especially in graphene-django.
my question is how can we create filtered query in schema.py in graphene-django project without using Relay feature? i saw this before but i don't want to use Relay feature. rather than i want use a filter, but i don't know how?? now my models.py and schema.py look-like these:
*models.py
# shoes_store/ingredients/models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=50)
notes = models.TextField(default='')
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=300)
descreption = models.TextField(default='')
price = models.CharField(max_length=50, default='')
imageURL = models.TextField(default='')
category= models.ForeignKey(Category,on_delete=models.CASCADE)
def __str__(self):
return self.name
and schema.py:
import graphene
from graphene_django.types import DjangoObjectType
from shoes_store.ingredients.models import Category, Product
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class ProductType(DjangoObjectType):
class Meta:
model = Product
class Query:
#===========================
# product
products = graphene.List(ProductType)
product = graphene.Field(ProductType,product_id=graphene.ID())
def resolve_products(self, info, **kwargs):
# Querying a list
return Product.objects.all()
def resolve_product(self, info, product_id):
# Querying a single user
return Product.objects.get(pk=product_id)
#===========================
# product_category
categories = graphene.List(CategoryType)
category = graphene.Field(CategoryType,category_id=graphene.ID())
def resolve_categories(self, info, **kwargs):
# Querying a list
return Category.objects.all()
def resolve_category(self, info, category_id):
# Querying a single user
return Category.objects.get(pk=category_id)
the best solution is look-like this if you don't want use Relay.
you can change your schema.py similar to:
import graphene
from graphene_django.types import DjangoObjectType
from shoes_store.ingredients.models import Category, Product
from django.db.models import Q
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class ProductType(DjangoObjectType):
class Meta:
model = Product
class Query:
#===========================
# product
products = graphene.List(ProductType,name=graphene.String(),category_id=graphene.ID())
product = graphene.Field(ProductType,product_id=graphene.ID())
def resolve_products(self, info, name=None,category_id=None, **kwargs):
# Querying a list
if name:
filter = (
Q(name__icontains=name) |
Q(descreption__icontains=name)
)
return Product.objects.filter(filter)
#
if category_id:
filter = (
Q(category_id__exact=category_id)
)
return Product.objects.filter(filter)
#
return Product.objects.all()
def resolve_product(self, info, product_id):
# Querying a single user
return Product.objects.get(pk=product_id)
#===========================
# product_category
categories = graphene.List(CategoryType)
category = graphene.Field(CategoryType,category_id=graphene.ID())
def resolve_categories(self, info, **kwargs):
# Querying a list
return Category.objects.all()
def resolve_category(self, info, category_id):
# Querying a single user
return Category.objects.get(pk=category_id)
now you can use different queries in your "http://127.0.0.1:8000/graphql" address. fore example you can use:
query{
products{
id
name
price
}
}
or even:
query{
products(categoryId:1){
id
name
price
}
}
or
query{
products(name:"Men's boots"){
id
name
price
}
}
I have Model called Games that has many posts connected by Model Posts. When I sort Games by Model Posts date posted it returns duplicates from Model Games. I'm wondering how I can display Games by most recent post date without returning duplicates.
Views.py
from django.shortcuts import render, get_object_or_404
from library.models import Game
from .models import Post
from django.views.generic import (
ListView,
DetailView
)
# Create your views here.
def home(request):
context = {
'recent': Game.objects.all().order_by('-post__date_published')[:5],
'posts': Post.objects.all(),
}
return render(request, 'main/home.html', context)
class TitlePostListView(ListView):
model = Post
template_name = 'main/title_posts.html'
context_object_name = 'posts'
paginate_by = 5
def get_queryset(self):
title = get_object_or_404(Game, title=self.kwargs.get('title'))
return Post.objects.filter(game=title).order_by('-date_published')
def get_context_data(self, **kwargs):
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = get_object_or_404(Game, title=self.kwargs.get('title'))
return context
class PostDetailView(DetailView):
model = Post
Models.py
class Post(models.Model):
article_title = models.CharField(max_length=100, default="Article Title Place Holder")
content = HTMLField(default="Article Content Pace Holder")
date_published = models.DateTimeField(default=timezone.now)
game = models.ForeignKey('library.Game', on_delete=models.CASCADE)
article_image = models.ImageField(default='/media/default.png')
class Game(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
cover = models.ImageField()
cover_display = models.ImageField(default='default.png')
developer = models.CharField(max_length=100)
What you are looking for here is distinct().
Game.objects.all().order_by('-post_set__date_published').distinct()[:5]
I also don't see where you are connecting Post and Game, so I am assuming that you are doing that in some other code that you haven't posted and that your current order_by is working.
I have a model 'Playlist' with an attribute 'private' that can be True or False (and therefore private or public). I want to use the #login_required decorator only if 'private = False', but can't figure out how to achieve this result. Here is my models.py file:
class Playlist(models.Model):
"""Allow a user to create a customized list of songs."""
name = models.CharField(max_length=100)
image = models.ImageField(upload_to='playlists/%Y/%m/%d', blank=True, null=True)
songs = models.ManyToManyField('Song')
description = models.TextField(blank=True, null=True, max_length=1000)
date_added = models.DateTimeField(auto_now_add=True)
private = models.BooleanField()
def __str__(self):
"""String for representing the model object."""
return self.name
def get_absolute_url(self):
"""Returns the url to access a detail record for this song."""
return reverse('playlist-detail', args=[str(self.id)])
And my views.py file:
def playlist(request, playlist_id):
"""Show a single playlist and associated data."""
playlist = Playlist.objects.get(id=playlist_id)
songs = playlist.songs.all()
for song in songs:
if song.url:
song.video_id = song.url.replace("https://www.youtube.com/watch?v=", "")
context = {'playlist': playlist, "playlist_songs": songs}
return render(request, 'great_songs_app/playlist.html', context)
I stumbled across a similar thread but there was no answer to the problem:Conditionally apply login_required decorator in Django
I imagine code looking something like what the OP posted, with the view function being preceded by:
if playlist.private == True:
#login_required
...
But obviously that won't work. Any ideas?
Rather than trying to apply #login_required, you could simply let the view undecorated and do something like the following, checking whether the user is authenticated:
from django.shortcuts import redirect
from django.conf import settings
def playlist(request, playlist_id):
"""Show a single playlist and associated data if user is authenticated."""
playlist = Playlist.objects.get(id=playlist_id)
if not playlist.private or (playlist.private and request.user.is_authenticated):
songs = playlist.songs.all()
for song in songs:
if song.url:
song.video_id = song.url.replace("https://www.youtube.com/watch?v=", "")
context = {'playlist': playlist, "playlist_songs": songs}
return render(request, 'great_songs_app/playlist.html', context)
else:
redirect(settings.LOGIN_URL)
I am trying to create two user types in django 1.3. I am subclassing the AUTH_PROFILE_MODULE with the following models.py:
class Member(models.Model):
ROLE_CHOICES = (
(0, 'Guide'),
(1, 'Operator'),
)
user = models.ForeignKey(User, unique=True)
location = models.CharField(max_length=60)
role = models.IntegerField(choices=ROLE_CHOICES)
class Guide(Member):
bio = models.TextField(blank=True)
experience = models.TextField(blank=True)
image = models.ImageField(blank=True, upload_to='images')
fileupload = models.FileField(blank=True, upload_to='files')
def __unicode__(self):
return self.user.username
def get_absolute_url(self):
return '/profiles/guides/%s' % self.user.username
class Operator(Member):
bio = models.TextField(blank=True)
image = models.ImageField(blank=True, upload_to='images')
def __unicode__(self):
return self.user.username
def get_absolute_url(self):
return '/profiles/operators/%s' % self.user.username
I am using generic class based views and can get the ListView to work for the Guide and Operator models I cannot get the DetailView to work. My views.py is as follows:
class GuideDetailView(DetailView):
model = Guide
context_object_name = 'guide'
template_name = 'members/guide_detail.html'
class GuideListView(ListView):
model = Guide
context_object_name = 'guides'
template_name = 'members/guide_list.html'
Any idea what might be missing?
Either provide a queryset:
class GuideDetailView(DetailView):
queryset = Guide.objects.all()
or override the get Method of DetailView:
class GuideDetailView(DetailView):
def get(self):
return "Everything you want, maybe: Guide.object.get(id=1)"
Given this in your urls.py:
url(r'^(?P<my_id>\d)/$', GuideDetailView.as_view(),),
You need to override get, like this:
class GuideDetailView(DetailView):
def get(self, request, **kwargs):
# lookup Guide Id in your database and assign it object
self.object = Guide.objects.get(pk=kwargs.get('my_id'))
# add object to your context_data, so that you can access via your template
context = self.get_context_data(object=self.object)
return self.render_to_response(context)