WIP: local changes

This commit is contained in:
2026-04-08 15:29:52 +03:00
parent 07842540ba
commit 81ba6cd076
56 changed files with 2015 additions and 0 deletions
+74
View File
@@ -0,0 +1,74 @@
from rest_framework import serializers
from .models import Contact, Relation
class ContactSerializer(serializers.ModelSerializer):
relations_count = serializers.SerializerMethodField()
class Meta:
model = Contact
fields = [
'id', 'name', 'email', 'phone',
'organization', 'position', 'notes',
'created_at', 'updated_at', 'relations_count',
]
read_only_fields = ['id', 'created_at', 'updated_at', 'relations_count']
def get_relations_count(self, obj):
return (
obj.relations_as_source.count() +
obj.relations_as_target.count()
)
class RelationSerializer(serializers.ModelSerializer):
source_name = serializers.CharField(source='source.name', read_only=True)
target_name = serializers.CharField(source='target.name', read_only=True)
class Meta:
model = Relation
fields = [
'id', 'source', 'source_name',
'target', 'target_name',
'relation_type', 'description', 'created_at',
]
read_only_fields = ['id', 'created_at', 'source_name', 'target_name']
def validate(self, data):
if data.get('source') == data.get('target'):
raise serializers.ValidationError(
'Нельзя создать связь контакта с самим собой.'
)
return data
class GraphSerializer(serializers.Serializer):
"""Граф для vis.js: nodes + edges."""
nodes = serializers.SerializerMethodField()
edges = serializers.SerializerMethodField()
def get_nodes(self, obj):
contacts = Contact.objects.all()
return [
{
'id': c.id,
'label': c.name,
'title': f'{c.organization}\n{c.position}'.strip() or c.name,
'group': c.organization or 'default',
}
for c in contacts
]
def get_edges(self, obj):
relations = Relation.objects.select_related('source', 'target').all()
return [
{
'id': r.id,
'from': r.source_id,
'to': r.target_id,
'label': r.get_relation_type_display(),
'title': r.description or r.get_relation_type_display(),
}
for r in relations
]