Модераторы: Daevaorn
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Более одного RelatedJoin (SQLObject), TurboGears и не только 
V
    Опции темы
pythonwin
  Дата 15.11.2006, 14:39 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник
Сообщений: 2529
Регистрация: 18.4.2006
Где: за компом

Репутация: 14
Всего: 36



Всем привет!

Взято с http://python.com.ua/forum/viewtopic.php?id=222

назрел вопрос:

как сделать Более одного RelatedJoin в таблице если они будут обращаться к одной и тойже таблице?

Код
from datetime import datetime
 
from sqlobject import *
 
from turbogears import identity 
from turbogears.database import PackageHub
 
hub = PackageHub("project")
__connection__ = hub
 
 
class VisitIdentity(SQLObject):
    visit_key = StringCol( length=40, alternateID=True,
                          alternateMethodName="by_visit_key" )
    user_id = IntCol()
 
 
class Group(SQLObject):
    """
    An ultra-simple group definition.
    """
    
    # names like "Group", "Order" and "User" are reserved words in SQL
    # so we set the name to something safe for SQL
    class sqlmeta:
        table="tg_group"
    
    group_name = UnicodeCol( length=16, alternateID=True,
                            alternateMethodName="by_group_name" )
    display_name = UnicodeCol( length=255 )
    created = DateTimeCol( default=datetime.now )
 
    # collection of all users belonging to this group
    users = RelatedJoin( "User", intermediateTable="user_group",
                        joinColumn="group_id", otherColumn="user_id" )
 
    # collection of all permissions for this group
    permissions = RelatedJoin( "Permission", joinColumn="group_id", 
                              intermediateTable="group_permission",
                              otherColumn="permission_id" )
 
 
class User(SQLObject):
    """
    Reasonably basic User definition. Probably would want additional attributes.
    """
    # names like "Group", "Order" and "User" are reserved words in SQL
    # so we set the name to something safe for SQL
    class sqlmeta:
        table="tg_user"
 
    user_name = UnicodeCol( length=16, alternateID=True,
                           alternateMethodName="by_user_name" )
    email_address = UnicodeCol( length=255, alternateID=True,
                               alternateMethodName="by_email_address" )
    display_name = UnicodeCol( length=255 )
    password = UnicodeCol( length=40 )
    created = DateTimeCol( default=datetime.now )
 
    # groups this user belongs to
    groups = RelatedJoin( "Group", intermediateTable="user_group",
                         joinColumn="user_id", otherColumn="group_id" )
    available_docs = RelatedJoin("Doc1", intermediateTable="readers_users_docs")
    MyDocs = RelatedJoin("Doc1", intermediateTable="writers_users_docs")
 
    def _get_permissions( self ):
        perms = set()
        for g in self.groups:
            perms = perms | set(g.permissions)
        return perms
        
    def _set_password( self, cleartext_password ):
        "Runs cleartext_password through the hash algorithm before saving."
        hash = identity.encrypt_password(cleartext_password)
        self._SO_set_password(hash)
        
    def set_password_raw( self, password ):
        "Saves the password as-is to the database."
        self._SO_set_password(password)
 
 
 
class Permission(SQLObject):
    permission_name = UnicodeCol( length=16, alternateID=True,
                                 alternateMethodName="by_permission_name" )
    description = UnicodeCol( length=255 )
    
    groups = RelatedJoin( "Group",
                        intermediateTable="group_permission",
                         joinColumn="permission_id", 
                         otherColumn="group_id" )
 
 
class Doc1(SQLObject):
    name = UnicodeCol() ## 
    description = UnicodeCol() ##
    readers = RelatedJoin("User", intermediateTable='readers_users_docs')
    writers = RelatedJoin("User", intermediateTable='writers_users_docs')



создать таблицы - я создам, правда не через tg-admin, а через CREATE TABLE , но вот потом как добавлять/удалять значения в readers и writers ?
addUser - срабатывает только для одного из них.


Цитата
TurboGears Version Info

    * turbogears 0.9a6
    * nose 0.8.6
    * configobj 4.3.1
    * ruledispatch 0.5a0.dev-r2115
    * setuptools 0.6a11
    * formencode 0.5.1
    * celementtree 1.0.5-20051216
    * pastescript 0.5.1
    * elementtree 1.2.6
    * simplejson 1.3
    * sqlobject 0.7.1dev-r1675
    * cherrypy 2.2.1
    * turbokid 0.9.5
    * turbocheetah 0.9.5
    * turbojson 0.9.2
    * pyprotocols 1.0a0dev-r2082
    * cheetah 1.0
    * pastedeploy 0.5
    * paste 0.5
    * formencode 0.5.1
    * kid 0.9.1
    * cheetah 1.0
    * elementtree 1.2.6

Installed Plugins
Identity Providers

    * sqlobject (turbogears 0.9a6)
    * sqlalchemy (turbogears 0.9a6)

tg-admin Commands

    * info (turbogears 0.9a6)
    * shell (turbogears 0.9a6)
    * quickstart (turbogears 0.9a6)
    * update (turbogears 0.9a6)
    * sql (turbogears 0.9a6)
    * i18n (turbogears 0.9a6)
    * toolbox (turbogears 0.9a6)

Visit Managers

    * sqlobject (turbogears 0.9a6)
    * sqlalchemy (turbogears 0.9a6)

Template Engines

    * kid (turbokid 0.9.5)
    * cheetah (turbocheetah 0.9.5)
    * json (turbojson 0.9.2)

Widget Packages

    * dominclude (dominclude 1.0)
    * lightbox (lightbox 2.0-p1)
    * scriptaculous (scriptaculous 1.6)
    * jumpmenu (jumpmenu 1.0)
    * moofx (moofx 1.2.4w2)
    * tinymce (turbotinymce 1.0.3)
    * selectshuttle (select-shuttle 0.94)
    * mywidgets (mywidgets 1.0)

TurboGears Extensions

    * visit (turbogears 0.9a6)
    * identity (turbogears 0.9a6)
    * fastdata (tgfastdata 0.9a6)

ОС == WinXP
СУБД == PostgreSQL

Это сообщение отредактировал(а) pythonwin - 15.11.2006, 15:44
PM WWW GTalk Jabber   Вверх
pythonwin
Дата 15.11.2006, 15:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник
Сообщений: 2529
Регистрация: 18.4.2006
Где: за компом

Репутация: 14
Всего: 36



БД и таблицы создал, данные ввел, но при добавлении связей между User и Doc1 в readers добавляется, а в writers - нет

Код

d1=Doc1.get(1) 
for x in dir(d1): print x


Цитата

SelectResultsClass
_SO_addUser
_SO_cleanDeprecatedAttrs
_SO_createValues
_SO_depends
_SO_fetchAlternateID
_SO_finishCreate
_SO_finishedClassCreation
_SO_foreignKey
_SO_from_python_description
_SO_from_python_name
_SO_getID
_SO_getValue
_SO_get_description
_SO_get_name
_SO_get_readers
_SO_get_writers
_SO_loadValue
_SO_removeUser
_SO_selectInit
_SO_setValue
_SO_set_description
_SO_set_name
_SO_setupSqlmeta
_SO_to_python_description
_SO_to_python_name
_SO_validatorState
_SO_writeLock
__class__
__classinit__
__delattr__
__dict__
__doc__
__getattribute__
__hash__
__init__
__metaclass__
__module__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__str__
__weakref__
_cacheValues
_childClasses
_columnDict
_columns
_connection
_create
_defaultOrder
_expired
_findAlternateID
_fromDatabase
_getJoinsToCreate
_get_description
_get_name
_get_readers
_get_writers
_idName
_idType
_inheritable
_init
_lazyUpdate
_notifyFinishClassCreation
_parent
_parentClass
_registry
_reprItems
_set_description
_set_name
_style
_table
addColumn
addIndex
addJoin
addUser
childName
clearTable
coerceID
createIndexes
createIndexesSQL
createJoinTables
createJoinTablesSQL
createTable
createTableSQL
delColumn
delIndex
delJoin
delete
description
destroySelf
dirty
dropJoinTables
dropTable
expire
get
getSchema
id
name
q
readers
removeUser
select
selectBy
set
setConnection
sqlmeta
sqlrepr
sync
syncUpdate
writers


Внимание!!! Только ОДИН addUser и срабатывает только для readers
PM WWW GTalk Jabber   Вверх
pythonwin
Дата 29.11.2006, 13:54 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник
Сообщений: 2529
Регистрация: 18.4.2006
Где: за компом

Репутация: 14
Всего: 36



проблему решил:

Код

from datetime import datetime

from sqlobject import *

from turbogears import identity 
from turbogears.database import PackageHub

hub = PackageHub("pr1")
__connection__ = hub


# class YourDataClass(SQLObject):
#     pass



class VisitIdentity(SQLObject):
    visit_key = StringCol( length=40, alternateID=True,
                          alternateMethodName="by_visit_key" )
    user_id = IntCol()


class Group(SQLObject):
    """
    An ultra-simple group definition.
    """
    
    # names like "Group", "Order" and "User" are reserved words in SQL
    # so we set the name to something safe for SQL
    class sqlmeta:
        table="tg_group"
    
    group_name = UnicodeCol( length=16, alternateID=True,
                            alternateMethodName="by_group_name" )
    display_name = UnicodeCol( length=255 )
    created = DateTimeCol( default=datetime.now )

    # collection of all users belonging to this group
    users = RelatedJoin( "User", intermediateTable="user_group",
                        joinColumn="group_id", otherColumn="user_id" )

    # collection of all permissions for this group
    permissions = RelatedJoin( "Permission", joinColumn="group_id", 
                              intermediateTable="group_permission",
                              otherColumn="permission_id" )


class User(SQLObject):
    """
    Reasonably basic User definition. Probably would want additional attributes.
    """
    # names like "Group", "Order" and "User" are reserved words in SQL
    # so we set the name to something safe for SQL
    class sqlmeta:
        table="tg_user"

    user_name = UnicodeCol( length=16, alternateID=True,
                           alternateMethodName="by_user_name" )
    email_address = UnicodeCol( length=255, alternateID=True,
                               alternateMethodName="by_email_address" )
    display_name = UnicodeCol( length=255 )
    password = UnicodeCol( length=40 )
    created = DateTimeCol( default=datetime.now )

    # groups this user belongs to
    groups = RelatedJoin( "Group", intermediateTable="user_group",
                         joinColumn="user_id", otherColumn="group_id" )
    available_docs = RelatedJoin("Doc1", intermediateTable="readers_users_docs", addRemoveName="av_Doc")
    MyDocs = RelatedJoin("Doc1", intermediateTable="writers_users_docs", addRemoveName="My_Doc")

    def _get_permissions( self ):
        perms = set()
        for g in self.groups:
            perms = perms | set(g.permissions)
        return perms
        
    def _set_password( self, cleartext_password ):
        "Runs cleartext_password through the hash algorithm before saving."
        hash = identity.encrypt_password(cleartext_password)
        self._SO_set_password(hash)
        
    def set_password_raw( self, password ):
        "Saves the password as-is to the database."
        self._SO_set_password(password)



class Permission(SQLObject):
    permission_name = UnicodeCol( length=16, alternateID=True,
                                 alternateMethodName="by_permission_name" )
    description = UnicodeCol( length=255 )
    
    groups = RelatedJoin( "Group",
                        intermediateTable="group_permission",
                         joinColumn="permission_id", 
                         otherColumn="group_id" )


class Doc1(SQLObject):
    name = UnicodeCol() ## 
    description = UnicodeCol() ##
    writers = RelatedJoin("User", intermediateTable='writers_users_docs', addRemoveName="writer")
    readers = RelatedJoin("User", intermediateTable='readers_users_docs', addRemoveName="reader")



использую addRemoveName из RelatedJoin and SQLRelatedJoin: Many-to-Many
PM WWW GTalk Jabber   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Python: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0705 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.