একটি পেতে as_dictআমার ক্লাস সব পদ্ধতি আমি একটি ব্যবহৃত Mixinবর্গ যা কলাকৌশল বর্ণনা ব্যবহার পিঁপড়া Aasma ।
class BaseMixin(object):
def as_dict(self):
result = {}
for prop in class_mapper(self.__class__).iterate_properties:
if isinstance(prop, ColumnProperty):
result[prop.key] = getattr(self, prop.key)
return result
এবং তারপরে আপনার ক্লাসে এটির মতো ব্যবহার করুন
class MyClass(BaseMixin, Base):
pass
এইভাবে আপনি উদাহরণের সাহায্যে নিম্নলিখিতটি প্রার্থনা করতে পারেন MyClass।
> myclass = MyClass()
> myclass.as_dict()
আশাকরি এটা সাহায্য করবে.
আমি এটিকে আরও খানিকটা আগে খেলেছি, আমার প্রকৃতপক্ষে এইচএল অবজেক্টেরdict রূপ হিসাবে সম্পর্কিত বিষয়গুলির সাথে সম্পর্কিত আমার উদাহরণগুলি রেন্ডার করা দরকার । সুতরাং আমি এখানে এই সামান্য যাদু যোগ করেছি, যা উপরের হিসাবে শ্রেণীর সমস্ত বৈশিষ্ট্য উপর ক্রল হবে এই পার্থক্যের সাথে যে আমি আরও গভীরতর বৈশিষ্ট্যগুলিতে ক্রল করব এবং এগুলির জন্য স্বয়ংক্রিয়ভাবে উত্পন্ন করব ।Relaionshiplinks
দয়া করে মনে রাখবেন যে এটি কেবলমাত্র একক প্রাথমিক কীতে সম্পর্কের জন্য কাজ করবে
from sqlalchemy.orm import class_mapper, ColumnProperty
from functools import reduce
def deepgetattr(obj, attr):
"""Recurses through an attribute chain to get the ultimate value."""
return reduce(getattr, attr.split('.'), obj)
class BaseMixin(object):
def as_dict(self):
IgnoreInstrumented = (
InstrumentedList, InstrumentedDict, InstrumentedSet
)
result = {}
for prop in class_mapper(self.__class__).iterate_properties:
if isinstance(getattr(self, prop.key), IgnoreInstrumented):
continue
if isinstance(prop, ColumnProperty):
result[prop.key] = getattr(self, prop.key)
if isinstance(prop, RelationshipProperty):
if 'links' not in result:
result['links'] = {}
value = (
deepgetattr(
self, prop.key + "." + prop.mapper.primary_key[0].key
)
)
result['links'][prop.key] = {}
result['links'][prop.key]['href'] = (
"/{}/{}".format(prop.key, value)
)
return result
__table__.columnsআপনাকে এসকিউএল ক্ষেত্রের নাম দেবে, আপনি নিজের ওআরএম সংজ্ঞাগুলিতে ব্যবহার করেছেন এমন বৈশিষ্ট্যগুলির নাম নয় (যদি দুটি পৃথক হয়)।