Skip to content

Instantly share code, notes, and snippets.

@dj-shin
Created August 7, 2017 04:29
Show Gist options
  • Save dj-shin/52457fa133933eb9dbf9623011487298 to your computer and use it in GitHub Desktop.
Save dj-shin/52457fa133933eb9dbf9623011487298 to your computer and use it in GitHub Desktop.
from django.db import models
from django.core.serializers.python import Serializer
class Tag(models.Model):
name = models.CharField(primary_key=True, max_length=32)
def __str__(self):
return f'{self.name}'
class Resource(models.Model):
title = models.CharField(max_length=256)
url = models.URLField()
tags = models.ManyToManyField(Tag)
def __str__(self):
return f'{self.title}'
class Connection(models.Model):
REFERENCE = 'REF'
relation_choices = (
(REFERENCE, 'Reference'),
)
relation = models.CharField(max_length=3, choices=relation_choices)
source = models.ForeignKey(Resource, models.CASCADE, related_name='source')
target = models.ForeignKey(Resource, models.CASCADE, related_name='target')
def __str__(self):
return f'{self.source.name} -{self.relation}-> {self.target.name}'
class Meta:
unique_together = ('source', 'target', 'relation')
ordering = ['source', 'target']
from django.http.response import JsonResponse
from network.models import Resource, Connection
from django.core.serializers import serialize
def network(request):
nodes = Resource.objects.all().prefetch_related('tags')
links = Connection.objects.all()
return JsonResponse({
'nodes': serialize('python', nodes),
'links': serialize('python', links),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment