Two classes: one for the django model and one for representing data outside of django

Is there a reasonable template for handling an object that exists as a Django model in the context of a specific Django application, and as a class other than Django, outside of that specific application?

For example, let's say that I have a Post model in the Django application blog. I want to be able to interact with a class representing this post outside the Django blog application, and possibly in another Django application.

In the past, I just created two completely different classes with slightly different interfaces. The Django model contains methods from both methods for creating from a version other than Django, or for exporting to a version other than Django. But for me this is not so.

EDIT: I understand that my language and use of the word "access" are confused. I am not asking how to talk to a Django application, I am asking how to have a Django model class and a non-Django class, present the same data with the same interface where I can export a Django model object to non-Django, so I can use him in another application. Errr, perhaps it was not clear or not?

+3
source share
3 answers

, , . , Django, , Django, , Django . , , , , , , (Django ).

Java #, - :

interface IFoo { ... }
class FooHelper { ... }
class app1.Foo extends Model implements IFoo { ... }
class app2.Foo implements IFoo { ... }

, IFoo, app1.Foo, app2.Foo , FooHelper. , bar :

interface IFoo { 
    int bar(); 
}

class FooHelper { 
    int bar( object foo ) { ... } 
}

package app1;
class Foo extends Model implements IFoo {
    ...
    int bar() {
        return FooHelper.bar( this );
    }
}

package app2;
class Foo implements IFoo {
    ...
    int bar() {
        return FooHelper.bar( this );
    }
}

, FooHelper , , Foo .

Python , Python .

# Create a class decorator
def decorate_foo( fooclass ):

    def bar( self ):
        return 0

    fooclass.bar = bar

# Create a class to decorate
class Foo: pass

# Decorate the class
decorate_foo( Foo )

# Use the decorated class
f = Foo()
f.bar()

decorate_foo, , .

+2

Django ( ). Python, Django, , , ORM, , :

from django.core.management import setup_environ
from mysite import settings
from myapp.models import MyModel

setup_environ(settings)

# Now do whatever you want with the ORM
mystuff = MyModel.objects.all()

, .

, Django , - , Django.

, , , API, Django, , , - , REST API. .

+2

, " Django". , ? - , , HTTP?

, RESTful API , HTTP. django-piston . , ?

0
source

Source: https://habr.com/ru/post/1759584/


All Articles