Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

54 lines
2.4KB

  1. # @name: relationships.py
  2. # @creation_date: 2022-04-11
  3. # @license: The MIT License <https://opensource.org/licenses/MIT>
  4. # @author: Simon Bowie <ad7588@coventry.ac.uk>
  5. # @purpose: functions for relationships
  6. # @acknowledgements:
  7. from flask import Blueprint, render_template, request, flash, redirect, url_for
  8. from .models import Resource
  9. from .models import Relationship
  10. from werkzeug.exceptions import abort
  11. from . import db
  12. # function to retrieve linked resources
  13. def get_relationships(primary_id):
  14. primary_relationships = Relationship.query.filter_by(first_resource_id=primary_id).all()
  15. links = []
  16. if primary_relationships:
  17. links = []
  18. for relationship in primary_relationships:
  19. secondary_id = relationship.second_resource_id
  20. links.extend(Resource.query.filter_by(id=secondary_id).all())
  21. secondary_relationships = Relationship.query.filter_by(second_resource_id=primary_id).all()
  22. if secondary_relationships:
  23. for relationship in secondary_relationships:
  24. primary_id = relationship.first_resource_id
  25. links.extend(Resource.query.filter_by(id=primary_id).all())
  26. return links
  27. else:
  28. secondary_relationships = Relationship.query.filter_by(second_resource_id=primary_id).all()
  29. if secondary_relationships:
  30. links = []
  31. for relationship in secondary_relationships:
  32. primary_id = relationship.first_resource_id
  33. links.extend(Resource.query.filter_by(id=primary_id).all())
  34. return links
  35. # function to add a relationship to a linked resource
  36. def add_relationship(resource_id, linked_resource_id):
  37. first_resource_id = resource_id
  38. second_resource_id = linked_resource_id
  39. new_relationship = Relationship(first_resource_id=first_resource_id, second_resource_id=second_resource_id)
  40. # add the new relationship to the database
  41. db.session.add(new_relationship)
  42. db.session.commit()
  43. # function to delete a single relationship
  44. def delete_relationship(main_id, for_deletion_id):
  45. relation = Relationship.query.filter(((Relationship.first_resource_id == main_id) & (Relationship.second_resource_id == for_deletion_id)) | ((Relationship.first_resource_id == for_deletion_id) & (Relationship.second_resource_id == main_id))).first()
  46. deletion = Relationship.query.get(relation.id)
  47. db.session.delete(deletion)
  48. db.session.commit()