fullstack GraphQL 学习笔记(14)links and votes

1、Attaching Users to Links

在links models.py中

from django.conf import settings

//增加字段
posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)

  然后更新数据库:

python manage.py makemigrations
python manage.py migrate

  在links/schema.py中的create_link增加post_by字段

class CreateLink(graphene.Mutation):
    id = graphene.Int()
    url = graphene.String()
    description = graphene.String()
    content = graphene.String()
    posted_by = graphene.Field(UserType)

    #2
    class Arguments:
        url = graphene.String()
        description = graphene.String()
        content = graphene.String()

    #3
    def mutate(self, info, url, description,content):
        user = info.context.user or None
        link = Link(url=url, description=description,content =content,posted_by=user)
        link.save()

        return CreateLink(
            id=link.id,
            url=link.url,
            description=link.description,
            content=link.content,
            posted_by=link.posted_by,
        )

  测试使用前,确保头部文件包含了token.

mutation{
	createLink(url:"http://sina.com",description:"sina"){
		id
		url
		description
		postedBy{
			id
			username
			password
		}
	}
}

  2、Adding Votes

(1)在links/model.py中增加投票模型

class Vote(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    link = models.ForeignKey('links.Link', related_name='votes', on_delete=models.CASCADE)

  

(2)更新数据库

python manage.py makemigrations
python manage.py migrate

  

(3)在schema.py中增加vote mutation

from .models import Link,Vote
from users.schema import UserType

class CreateVote(graphene.Mutation):
    user = graphene.Field(UserType)
    link = graphene.Field(LinkType)

    class Arguments:
        link_id = graphene.Int()

    def mutate(self, info, link_id):
        user = info.context.user
        if user.is_anonymous:
            raise Exception('You must be logged to vote!')

        link = Link.objects.filter(id=link_id).first()
        if not link:
            raise Exception('Invalid Link!')

        Vote.objects.create(
            user=user,
            link=link,
        )

        return CreateVote(user=user, link=link)

  

 

posted @ 2018-08-29 12:20  tutu_python  阅读(147)  评论(0)    收藏  举报