App Design in Django - django

I have a general algorithm design question. I am creating a Django app that will connect to an API, but I won't be storing these results (at least not at first). After I retrieve the data from the API I manipulate it accordingly and have already created a class with numerous methods to do this.
Should the programming logic for this be performed in the model or the view for the Django framework? Is one more sustainable than the other (e.g. in a few months I decide to store the information). Also, is it best to encapsulate my class in its own file, and them import into the model/view?
Thanks!
Rob

If you don't need to store data, don't use Djnago's built in models.
Write views and import your own modules/classes.
Bonus: If your views share a lot of logic (probably related to request/response handling), use class based views and write a common MyBaseView.

Related

Creating nested objects in Django REST Framework

What is the rightâ„¢ way to design DRF serializers that receive the following POSTed data to a List model:
{
list_name: "friends",
contacts: ["alice", "bob"]
}
And handles the creation of the nested Contact objects? Additionally, assume an extra step is needed to convert the names to capitalized (['Alice', 'Bob']).
You could use django-rest-framework-bulk which is linked from Django Rest Framework's documentation: http://www.django-rest-framework.org/topics/third-party-resources#views
'Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.'
I'm not sure if it's the 'rightâ„¢' way of doing it but the library is being actively maintained and it's 9 months old and seems to have a few contributors. Worth looking into.

Django design patterns for overriding models

I'm working on an e-commerce framework for Django. The chief design goal is to provide the bare minimum functionality in terms of models and view, instead allowing the users of the library to extend or replace the components with their own.
The reasoning for this is that trying to develop a one-size-fits-all solution to e-commerce leads to overcomplicated code which is often far from optimal.
One approach to tackling this seems to be using inversion-of-control, either through Django's settings file or import hacks, but I've come up against a bit of a problem due to how Django registers its models.
The e-commerce framework provides a bunch of abstract models, as well as concrete versions in {app_label}/models.py. Views make use of Django's get_model(app_label,model) function to return the model class without having to hard-code the reference.
This approach has some problems:
Users have to mimic the structure of the framework's apps, ie the app_label and effectively replace our version of the app with their own
Because of the way the admin site works by looking for admin.py in each installed app, they have to mimic or explicitly import the framework's admin classes in order to use them. But by importing them, the register method gets called so they have to be unregistered if a user wants to customise them.
The user has to be extremely careful about how they import concrete models from the core framework. This is because Django's base model metaclass automatically registers a model with the app cache as soon as the class definition is read (ie upon __new__), and the first model registered with a specific label is the one you're stuck with. So you have to define all your override models BEFORE you import any of the core models. This means you end up with messy situations of having a bunch of imports at the bottom of your modules rather than the top.
My thinking is to go further down the inversion-of-control rabbit hole:
All references to core components (models, views, admin, etc) replaced with calls to an IoC container
For all the core (e-commerce framework) models, replace the use of Django's base model metaclass with one that doesn't automatically register the models, then have the container explicitly register them on startup.
My question:
Is there a better way to solve this problem? The goal is to make it easy to customise the framework and override functionality without having to learn lots of annoying tricks. The key seems to be with models and the admin site.
I appreciate that using an IoC container isn't a common pattern in the Django world, so I want to avoid it if possible, but it is seeming like the right solution.
Did you look at the code from other projects with a similar approach?
Not sure if this way covers your needs, but imo the code of django-shop is worth to look at.
This framework provides the basic logic, allowing you to provide custom logic where needed.
customize via models
eg see the productmodel.py
#==============================================================================
# Extensibility
#==============================================================================
PRODUCT_MODEL = getattr(settings, 'SHOP_PRODUCT_MODEL',
'shop.models.defaults.product.Product')
Product = load_class(PRODUCT_MODEL, 'SHOP_PRODUCT_MODEL')
customize via logic/urls
eg see the shop's simplevariation-plugin
It extends the cart-logic, so it hooks in via urlpattern:
(r'^shop/cart/', include(simplevariations_urls)),
(r'^shop/', include(shop_urls)),
and extends the views:
...
from shop.views.cart import CartDetails
class SimplevariationCartDetails(CartDetails):
"""Cart view that answers GET and POSTS request."""
...
The framework provides several points to hook-in, the simplevariation-plugin mentionned above additionally provides a cart-modifier:
SHOP_CART_MODIFIERS = [
...
'shop_simplevariations.cart_modifier.ProductOptionsModifier',
...
]
I worry that this explanation is not very understandable, it is difficult to briefly summarize this concept. But take a look at the django-shop project and some of its extensions: ecosystem

What are the use cases for class based generic views for django

I am trying to write some generic boiler plate code for creating facebook apps. I am writing a separate FacebookUser class instead of django's standrd contrib.user app. I am wondering if it would be a good design decision to actually write all oauth steps using class based generic views . What is the point of using class based genric views and why and where should i use them
Any Repetitve process that would benefit from an object oriented approach. For me I create a lot of utilities that allows users to download data as a CSV, I have implemented a CSVResponseView view that returns a csv with the correct content types. This makes it easier for me to test, and lends itself to a more consistent easier to maintain implementation then function based views.

How should multiple Django apps communicate with each other?

Other posters have previously said in this forum that when your Django app starts getting big and unmanageable, you should split it up into several apps. I'm at that point now. What are the best practices for allowing communication between these apps?
One of my apps (let's call it Processor) processes very large data sets. Once an hour it produces a small amount of new data for the other app. This other app (let's call it Presenter) displays the data to users.
How should Processor hand new data to Presenter? Should it simply import parts of Presenter's model, so it can create and save records in Presenter's database? That seems like tight coupling to me. Or should it pass the data by calling a function in Presenter? Or put the data in some sort of data store that both Processor and Presenter know about?
How do you all usually solve this problem?
/Martin
I would definitely go for the importing Processor's models in the Presenter app. That's how, for instance, you can add extra user info: you have a UserPreferences model with a ForeignKeyField to django.contrib.auth.models.User. Your might have less of a bad feeling doing that that between your two apps because django.contrib is the "standard library", but nevertheless, it is direct coupling.
If your applications are coupled, then your code should be coupled to reflect this. This follows the idea that explicit is better than implicit, right?
If, however, your're designing something a tad more generic (i.e. you're going to use multiple Presenter app instances for Processors of different kinds), you can store the specific models as a setting:
import processor_x.models
PRESENTER_PROCESSOR_MODELS = presenter_x.models
Then, in your Presenter models:
from django.conf import settings
class Presenter:
processor = models.ForeignKey(settings.PRESENTER_PROCESSOR_MODELS)
Caveat: I have never attempted this, but I don't recall a limitation on settings to be only strings, tuples or lists!

Sharing view logic in Django

I've begun diving into Django again and I'm having trouble finding the parallel to some common concepts from my life in C#. While using .NET MVC I very often find myself creating a base controller which will provide a base action implementation to take care of the type of stuff I want to do on every request, like retrieving user information, getting localization values.
Where I'm finding myself confused is how to do this in Django. I am getting more familiar with the MVT concept but I can't seem to find how to solve this scenario. I've looked at class based views and the generic views yet they didn't seem to work how I expected. What am I missing? How can i create default logic that each view will be instructed to run but not have to write it in each view method?
If it is truly common for your whole site you use middleware. If it is only common for some views, the way to go in my opinion is to create decorators for those views. I never use class-based views because I tend to keep views simple and put more logic into models, so I have no need for classes there.