Skip to content

Commit

Permalink
model update (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevegerrits authored Mar 27, 2024
1 parent 806e464 commit 5e868b2
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 55 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Generated by Django 5.0.3 on 2024-03-27 13:34

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('observations', '0004_rename_lengte_municipality_length_and_more'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.AddField(
model_name='observation',
name='anb',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='observation',
name='reserved_by',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='reserved_observations', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='observation',
name='reserved_datetime',
field=models.DateTimeField(blank=True, null=True),
),
]
49 changes: 30 additions & 19 deletions vespadb/observations/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,12 @@ class EradicationProductEnum(models.TextChoices):
class Municipality(models.Model):
"""Model voor de Belgische gemeenten met uitgebreide gegevens."""

# Behoud de bestaande velden
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255) # Overeenkomend met 'NAAM'
nis_code = models.CharField(max_length=255) # Overeenkomend met 'NISCODE'
polygon = gis_models.MultiPolygonField(srid=31370) # Zorg voor het juiste SRID, bv. Belgian Lambert 72
name = models.CharField(max_length=255)
nis_code = models.CharField(max_length=255)
polygon = gis_models.MultiPolygonField(srid=31370)

# Nieuwe velden gebaseerd op de extra informatie
oidn = models.BigIntegerField(blank=True, null=True) # Optioneel, afhankelijk van de behoefte
oidn = models.BigIntegerField(blank=True, null=True)
uidn = models.BigIntegerField(blank=True, null=True)
terrid = models.BigIntegerField(blank=True, null=True)
datpublbs = models.DateField(blank=True, null=True)
Expand Down Expand Up @@ -116,43 +114,56 @@ class Observation(models.Model):
created_datetime = models.DateTimeField(auto_now_add=True)
modified_datetime = models.DateTimeField(auto_now=True)
location = gis_models.PointField()
municipality = models.ForeignKey(
Municipality,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="observations",
)
source = models.CharField(max_length=255)

wn_notes = models.TextField(blank=True, null=True)
wn_admin_notes = models.TextField(blank=True, null=True)

species = models.IntegerField()
nest_height = models.CharField(max_length=50, choices=NestHeightEnum)
nest_size = models.CharField(max_length=50, choices=NestSizeEnum)
nest_location = models.CharField(max_length=50, choices=NestLocationEnum)
nest_type = models.CharField(max_length=50, choices=NestTypeEnum)

observer_phone_number = models.CharField(max_length=20, blank=True, null=True)
observer_email = models.EmailField(blank=True, null=True)
observer_name = models.CharField(max_length=255, blank=True, null=True)
observer_allows_contact = models.BooleanField(default=False)
observation_datetime = models.DateTimeField()

wn_cluster_id = models.IntegerField(blank=True, null=True)
notes = models.TextField(blank=True, null=True)

modified_by = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name="modified_observations", on_delete=models.SET_NULL, null=True
)
created_by = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name="created_observations", on_delete=models.SET_NULL, null=True
)
modified_by = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name="modified_observations", on_delete=models.SET_NULL, null=True
wn_modified_datetime = models.DateTimeField(blank=True, null=True)
wn_created_datetime = models.DateTimeField(blank=True, null=True)
duplicate = models.BooleanField(default=False)
images = models.JSONField(default=list)

reserved_by = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name="reserved_observations", on_delete=models.SET_NULL, null=True
)
reserved_datetime = models.DateTimeField(blank=True, null=True)

eradication_datetime = models.DateTimeField(blank=True, null=True)
eradicator_name = models.CharField(max_length=255, blank=True, null=True)
eradication_result = models.CharField(max_length=50, choices=EradicationResultEnum)
eradication_product = models.CharField(max_length=50, choices=EradicationProductEnum, blank=True, null=True)
eradication_notes = models.TextField(blank=True, null=True)
wn_modified_datetime = models.DateTimeField(blank=True, null=True)
wn_created_datetime = models.DateTimeField(blank=True, null=True)
duplicate = models.BooleanField(default=False)
images = models.JSONField(default=list)

municipality = models.ForeignKey(
Municipality,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="observations",
)
anb = models.BooleanField(default=False)

def __str__(self) -> str:
"""Return the string representation of the model."""
Expand Down
53 changes: 18 additions & 35 deletions vespadb/observations/serializers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
"""Serializers for the observations app."""

from typing import Any, cast
from typing import Any

from django.contrib.gis.geos import Point
from django.utils import timezone
from rest_framework import serializers

from vespadb.observations.models import Municipality, Observation
Expand All @@ -29,7 +28,18 @@ def to_representation(self, instance: Observation) -> dict[str, Any]:
data: dict[str, Any] = super().to_representation(instance)

# Fields accessible by public (unauthenticated) users
public_fields = ["id", "location", "nest_height", "nest_size", "nest_location", "nest_type", "created_by"]
public_fields = [
"id",
"location",
"nest_height",
"nest_size",
"nest_location",
"nest_type",
"created_by",
"eradiction_datetime",
"municipality",
"images",
]

# Check if the request exists and if the user is authenticated
request = self.context.get("request", None)
Expand Down Expand Up @@ -59,36 +69,6 @@ def validate_location(self, value: dict[str, float]) -> Point:

return Point(longitude, latitude)

def create(self, validated_data: dict[str, Any]) -> Observation:
"""Create a Observation instance from validated data, converting location data from a dictionary to a Point object suitable for the GeoDjango field.
Parameters
----------
- validated_data (Dict[str, Any]): The data validated by the serializer.
Returns
-------
- Observation: The created Observation instance.
"""
return cast(Observation, super().create(validated_data))

def update(self, instance: Observation, validated_data: dict[str, Any]) -> Observation:
"""Update an existing Observation instance with validated data, converting location data from a dictionary to a Point object when necessary.
Parameters
----------
- instance (Observation): The Observation instance to update.
- validated_data (Dict[str, Any]): The data validated by the serializer.
Returns
-------
- Observation: The updated Observation instance.
"""
# Set last_modification_datetime to now
instance.last_modification_datetime = timezone.now()

return cast(Observation, super().update(instance, validated_data))


class ObservationPatchSerializer(serializers.ModelSerializer):
"""Serializer for patching observations with limited fields accessible by exterminators or other specific roles. This serializer allows updating a subset of the Observation model's fields, ensuring that users can only modify fields they are authorized to."""
Expand All @@ -106,12 +86,14 @@ class Meta:
"notes",
"modified_by",
"created_by",
"duplicate",
"reserved_by",
"reserved_datetime",
"eradication_datetime",
"eradicator_name",
"eradication_result",
"eradication_product",
"eradication_notes",
"duplicate",
]
read_only_fields = [
"id",
Expand All @@ -122,10 +104,11 @@ class Meta:
"wn_notes",
"wn_admin_notes",
"species",
"wn_cluster_id",
"wn_modified_datetime",
"wn_created_datetime",
"images",
"municipality",
"anb",
]


Expand Down
2 changes: 1 addition & 1 deletion vespadb/observations/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def export(self, request: Request) -> HttpResponse:
class MunicipalityViewSet(ReadOnlyModelViewSet):
"""ViewSet for the Municipality model."""

queryset = Municipality.objects.all()
queryset = Municipality.objects.all().order_by("name")
serializer_class = MunicipalitySerializer

def get_permissions(self) -> list[BasePermission]:
Expand Down

0 comments on commit 5e868b2

Please sign in to comment.