Skip to content

Instantly share code, notes, and snippets.

@underlost
Created May 27, 2022 05:50
Show Gist options
  • Save underlost/bd12b9dc9c0def53664c4307bb77c88e to your computer and use it in GitHub Desktop.
Save underlost/bd12b9dc9c0def53664c4307bb77c88e to your computer and use it in GitHub Desktop.
A simple geoJSON Example
class Event(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=250, blank=True, null=True)
description = models.CharField(
blank=True,
null=True,
max_length=512,
help_text="Reading a book, watching a movie, etc",
)
content = models.TextField(blank=True, null=True)
content_html = models.TextField(editable=False, blank=True, null=True)
pub_date = models.DateTimeField(
verbose_name="When the event happened, or is going to happen.", blank=True, null=True
)
date_created = models.DateTimeField(auto_now_add=True, editable=False)
date_updated = models.DateTimeField(auto_now=True, editable=False)
is_public = models.BooleanField(help_text="Should be checked to show up on global timelines.", default=False)
is_active = models.BooleanField(help_text="Is it published?", default=False)
location = models.ForeignKey(Location, blank=True, null=True, on_delete=models.SET_NULL)
lnglat = models.JSONField(blank=True, null=True)
class GeoJsonEventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = [
"id",
"user",
"name",
"description",
"content_html",
"pub_date",
"date_updated",
"date_created",
"lnglat",
"location",
"timeline",
"image",
]
def to_representation(self, instance):
# instance is the model object. create the custom json format by accessing instance attributes normaly and return it
identifiers = dict()
identifiers["name"] = instance.name
identifiers["description"] = instance.description
representation = {
"type": "Feature",
"geometry": {"type": "Point", "coordinates": [instance.lnglat.get("Lng"), instance.lnglat.get("Lat")]},
"properties": {
"name": instance.name,
"description": instance.description,
"url": "http://fubar/",
},
}
return representation
class EventViewSet(ViewSet):
"""Events"""
permission_classes = [OwnsObjectOrReadOnly]
def list(self, request):
"""Get all public events"""
events = Event.objects.public()
serialized_data = GeoJsonEventSerializer(events, many=True, context={"request": request})
return Response(
{
"result": serialized_data.data,
}
)
def retrieve(self, request, pk=None):
"""Get an event"""
if request.user.is_authenticated:
event = get_object_or_404(Event, pk=pk)
else:
event = get_object_or_404(
Event,
pk=pk,
is_active=True,
is_public=True,
)
serialized_data = GeoJsonEventSerializer(event, context={"request": request})
return Response(
{
"result": serialized_data.data,
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment