Cannot access field in Django Graphene - django

The field which is specified in my models file is not included in the GraphiQL, I have tried to rename the field, delete it and define it again, even changing the type of field also updating the graphene-django package. None of these I have mentioned didn't work. The name of the field I can't get is named book
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from books.models import Book
class Borrowing(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
book = models.OneToOneField(Book, null=True, on_delete=models.CASCADE)
date = models.DateTimeField(default=timezone.now)
returned = models.BooleanField(default=False)
date_borrowed = models.CharField(blank=True, null=True, max_length=50)
date_returned = models.CharField(blank=True, null=True, max_length=50)
class Meta:
ordering = ['-date']
def __str__(self):
return f'{self.user.username} borrowed {self.book.title}'
schema.py
import graphene
from .mutations.borrowings import *
from backend.functions import pagination
PAGE_SIZE = 12
class BorrowingMutation(graphene.ObjectType):
borrow_book = BorrowBook.Field()
return_book = ReturnBook.Field()
class BorrowingQuery(graphene.ObjectType):
borrowings = graphene.List(BorrowingType)
users_borrowings = graphene.List(BorrowingType, page=graphene.Int())
def resolve_borrowings(self, info):
return Borrowing.objects.all()
def resolve_users_borrowings(self, info, page):
user = info.context.user
borrowings = Borrowing.objects.filter(user=user, returned=False)
borrowings = pagination(PAGE_SIZE, page, borrowings)
return borrowings
Type
class BorrowingType(DjangoObjectType):
class Meta:
model = Borrowing

Related

Mutation in django graphene for model with foreign key and many to many relationship

I have 2 models in my django app, the first is Tags model and the second is Post model, the problem is when i try to use mutation for the Post model to add a post from the graphql it doesn't work but it works fine in the Tags model, also the Queries works fine when i try to get data from the database.
Here's my Code:
model.py:
from django.db import models
from django.utils.translation import gettext as _
from django.conf import settings
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class Tag(models.Model):
name = models.CharField(_("Tag Name"), max_length=50, unique=True)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(_("Title"), max_length=50, unique=True)
slug = models.SlugField(_("Post Slug"), unique=True)
body = models.TextField(_("Post Content"))
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
published = models.BooleanField(_("Published"), default=False)
author = models.ForeignKey(User, verbose_name=_("Author"), on_delete=models.CASCADE)
tags = models.ManyToManyField("Tag", verbose_name=_("Tags"), blank=True)
class Meta:
ordering = ['-createdAt']
def __str__(self):
return self.title
schema.py:
import graphene
from graphene_django import DjangoObjectType
from django.contrib.auth import get_user_model
from .models import Post, Tag
User = get_user_model()
class PostType(DjangoObjectType):
class Meta:
model = Post
class TagType(DjangoObjectType):
class Meta:
model = Tag
fields = ('id', 'name',)
class TagInput(graphene.InputObjectType):
name = graphene.String(required=True)
class CreatePostMutation(graphene.Mutation):
class Arguments:
title = graphene.String()
body = graphene.String()
published = graphene.Boolean()
author_id = graphene.ID()
tags = graphene.List(graphene.Int)
success = graphene.Boolean()
post = graphene.Field(PostType)
#classmethod
def mutate(cls, root, info, title, body, published, author_id, tags):
author = User.objects.get(pk=author_id)
post_instance = Post(
title=title,
body=body,
published=published,
author=author,
)
post_instance.save(commit=False)
if tags:
tag_objects = Tag.objects.filter(pk__in=tags)
post_instance.tags.set(tag_objects)
post_instance.save()
return CreatePostMutation(success=True, post=post_instance)
class CreateTagMutation(graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
tag = graphene.Field(TagType)
#classmethod
def mutate(cls, root, info, name):
tag = Tag(name=name)
tag.save()
return CreateTagMutation(tag=tag)
class Mutation(graphene.ObjectType):
create_post = CreatePostMutation.Field()
create_tag = CreateTagMutation.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
Here's what it returns:
{
"data": {
"createPost": {
"post": null
}
}
}

NOT NULL constraint failed: shipping_ship.user_id Django

So I'm working on a shipping website with the django rest framework. The website brings two to four people together so they can easily ship their goods together at the same time. But I'm facing a major stumbling block on the views where user book a shipping the code is below.
models.py
from django.db import models
from django.contrib import get_user_model
User = get_user_model()
class Container(models.Model):
container_type = models.Charfield(max_length = 30, blank=False, null = False)
max_users = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places =2, default=0, blank=True, null=True)
users = models.ManyToManyField(User)
class Ship(models.Model):
container = models.ForeignKey(Container, related_name='cont', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='shipper', on_delete=models.CASCADE)
location = (
('France', 'France'),
)
from_location = models.CharField(max_length=30, choices=location, blank=False, null=False)
to_location = (
('Lagos', 'Lagos'),
('Abuja', 'Abuja'),
('Abeokuta', 'Abeokuta'),
('Osun', 'Osun'),
)
to_location = models.CharField(max_length=30, choices=to_location, blank=False, null=False)
date_leaving = models.DateField(auto_now=False)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True)
def __str__(self):
return self.user
then my serializer.py file
from rest_framework import serializers
from .models import Container, Ship
class ContainerSerializer(serializers.ModelSerializer):
class Meta:
model = Container
fields = '__all__'
class MiniContainerSerializer(serializers.ModelSerializer):
class Meta:
model = Container
fields =['container_type', 'price']
class ShipSerializer(serializers.ModelSerializer):
class Meta:
model = Ship
fields = '__all__'
read_only_fields = ('user', 'price')
class MiniShipSerializer(serializers.ModelSerializer):
class Meta:
model = Ship
fields = ['container', 'from_location', 'to_location']
and now my views.py file which I have issues with
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from rest_framework.generics import ListCreateAPIView, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView
from .serializers import ContainerSerializer, MiniContainerSerializer, ShipSerializer, MiniShipSerializer
from rest_framework import permissions, status
from rest_framework.response import Response
from .models import Container, Ship
class ShipAPI(ListCreateAPIView):
serializer_class = ShipSerializer
def get_queryset(self):
user = self.request.user
queryset = Ship.objects.filter(user=user)
return queryset
def Book_shipping(self, request, *args, **kwargs):
user = request.user
container = get_object_or_404(Container, pk=request.data['container'])
if container.users.count() >= container.max_users:
return Response('container already full')# here i'm trying to set limits so the users joining each container won't surpass the max users.
cont = container(users=user)
cont.save()
from_location = (request.data['from_location'])
to_location = (request.data['to_location'])
date_leaving = int(request.data['date_leaving'])
price = container.price / container.max_users
cart = Ship(container=container, user=user, from_location=from_location, to_location=to_location, date_leaving=date_leaving, price=price)
cart.save()
serializer = ShipSerializer(cart)
data ={'message': 'shipping successfully created',
'data':serializer.data}
return Response(data=data, status=status.HTTP_201_CREATED)
and then after testing the endpoint it returns this error:
IntegrityError at /Shipping/Ship/
NOT NULL constraint failed: shipping_ship.user_id
I've tried debugging and looking at it over and over again can someone please help me? Thanks in advance. And yes I've tried deleting migrations and the database.
As your Container model have a ManyToMany relationship with the User model.
So it may not work like cont = container(users=user)
For me it worked like this:
cont = container.users.add(user)
cont.save()

Django : change the id with another field in the views page

How do I tell to Django to replace the Column type_id to the name field in the views (html page).
and here I have foreignkey, it gave me id (type_id), and this screentshot of fabrication class:
the column type_id is comming from the composant_type class,
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.base import Model
from CentreCout.models import CentreCoutDB
class fiche(models.Model):
centre_cout = models.CharField(max_length=150)
number = models.CharField(max_length=100)
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class unite(models.Model):
name = models.CharField(max_length= 150, unique=True)
def __str__(self):
return self.name
class composant_type(models.Model):
name = models.CharField(max_length=150, unique=True )
def __str__(self):
return f"({self.name})"
class composant_fab(models.Model):
type = models.ForeignKey(composant_type, to_field='name', on_delete=models.CASCADE)
name = models.CharField(max_length=150, unique=True)
def __str__(self):
return f"({self.name})"
class fabrication(models.Model):
grade = models.ForeignKey(fiche, to_field='name',on_delete=models.CASCADE)
type = models.ForeignKey(composant_type, on_delete=models.CASCADE, blank=True, null=True)
composant = models.ForeignKey(composant_fab , to_field='name', on_delete=models.CASCADE, null=True, blank=True)
unite = models.ForeignKey(unite, to_field='name',on_delete=models.CASCADE)
composant_value = models.FloatField(blank=True, null=True)
def __str__(self):
return f"({self.grade}-{self.composant}-{self.composant_value}-{self.unite})"
views.py
from django.shortcuts import render
from django import views
from django.http import HttpResponse
from .models import *
import pandas as pd
def fabrications(request):
lesfichestab = fiche.objects.all()
fabricationtab = fabrication.objects.all().values()
df = pd.DataFrame(fabricationtab)
context = {
'lesfichestab':lesfichestab,
'fabricationtab':df.to_html()
}
return render(request,'fabrications/fabricationpage.html', context)
Note: I use Pandas method, because i have to do some Filtering and pivoting of the table.
I get an answer from here :
Django with Pandas accessing ForeignKey
admin_data = pd.DataFrame.from_records(
administrations.values(
"id",
"study__name", # <-- get the name through the foreign key
"url_hash",
)
).rename(
columns={
"id": "administration_id",
"study__name": "study_name",
"url_hash": "link",
}
)

Django model of a rent contract using Generic Foreign Key

I'm trying to model a rent contract in Django and use the admin form to insert and modify it.
Both owner and tenant can be companies (VAT number) or individuals (no VAT number). Companies and individuals are stored in two different models (Company and Individual).
I'm trying to solve this problem using Generic Foreign Key but I'm not able to show the tenant name in the admin page, only an integer field not friendly at all.
gestimm is the name of the app and that's my oversimplified models:
# my gestimm/models.py
#
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Individual(models.Model):
name = models.CharField(max_length=100, help_text='Name')
def __str__(self):
return self.name
class Company(models.Model):
name = models.CharField(max_length=100, help_text='Name')
def __str__(self):
return self.name
class Contract(models.Model):
description = models.CharField(max_length=30)
start = models.DateField()
stop = models.DateField()
def __str__(self):
return self.description
class Tenant(models.Model):
limit = models.Q(app_label='gestimm', model='individual') | models.Q(app_label='gestimm', model='company')
contract = models.ForeignKey(Contract, on_delete=models.CASCADE,
null=True, blank=True)
content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT,
help_text='Tenant', null=True,
limit_choices_to=limit)
object_id = models.PositiveIntegerField(null=True)
tenant = GenericForeignKey('content_type', 'object_id')
How I tried to solve the problem:
# my gestimm/admin.py
#
from django.contrib import admin
from .models import Individual, Company, Contract, Tenant
class TenantInline(admin.StackedInline):
model = Tenant
extra = 1
class ContractAdmin(admin.ModelAdmin):
inlines = [TenantInline]
admin.site.register(Individual)
admin.site.register(Company)
admin.site.register(Contract, ContractAdmin)
I found some old discussions but none of the proposed solutions worked.
Problem solved: I installed django-grappelli.
My new admin.py:
class TenantInline(admin.TabularInline):
model = Tenant
extra = 1
related_lookup_fields = {
'generic': [['content_type', 'object_id']],
}
class ContractAdmin(admin.ModelAdmin):
inlines = [
TenantInline,
]
admin.site.register(Contract, ContractAdmin)
As intended

how to populate django models randomly

I am following a tutorial online for Django. The presenter loads in random data as follows:
for i in xrange(100): Vote(link = Link.objects.order_by('?')[0],voter=a).save()
From what I could understand, it goes from 0 to 100 and creates a new vote. The vote object has a link object. I don't understand what the order_by('?') means.
Here is the model.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
class LinkVoteCountManager(models.Manager):
def get_query_set(self):
return super(LinkVoteCountManager, self).get_query_set().annotate(
votes=Count('vote')).order_by("-votes")
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, blank=True)
description = models.TextField(blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __unicode__(self):
return self.title
class Vote(models.Model):
voter = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __unicode__(self):
return "%s voted %s" %(self.voter.username, self.link.title)