What's the best way to keep queries ? - django

i'm poor with django.
i have a project and project has an app
in my app, i have a models.py and includes
from django.db import models
from taggit.managers import TaggableManager
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
created = models.DateTimeField()
tags = TaggableManager()
def __unicode__(self):
return self.title
and i also add this models.py
posts = Post.objects.all().order_by("-created")[:2]
Is it the right way to keep it here?
Some examples shows that queries in models.py some are in views.py ?
Also can i use posts in my mysite/templates ?

The best way to do this is to create a custom manager with a method that performs the query when called. That way you don't need to worry about it being cached, recycled, etc.

Related

Creating Model of Users and Posts Django

I am trying to learn Django by creating something similar to Reddit. I have models for Post and User, and now I want to create one for "Community". I have looked at this post:
How to store an array of users in django?
However, I am unsure if the ManyToMany relationship is right here (perhaps it is).
I want the Community Model to contain Posts and Users registered with the Community. Each Community can have many posts, and each user can belong to multiple communities. When a Community is deleted, only delete the posts in that community, not the users. Similarly, when a User is deleted or a Post deleted, just remove that aspect from the Community.
If anyone has done this before or knows of a resource to learn this please let me know.
Here is my Post model so far. Note my Communities are called "Bands". Thus all of my references to "Community" will be "Bands" in my project.
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# each class is its own table in the data
class Post(models.Model):
# each attribute is a different field in the data
title = models.CharField(max_length=100)
content = models.TextField()
# pass in the function as the default val, but do NOT execute yet!
date_posted = models.DateTimeField(default=timezone.now)
# foreign keys link two tables together
# on delete of User, we delete the user's post as well
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
Here is my Band model:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from home.models import Post
class Band(models.Model):
name = models.CharField(max_length = 100)
date_created = models.DateTimeField(default=timezone.now)
users = (settings.AUTH_USER_MODEL)
def __str__(self):
return "{self.name}"

djongo ArrayField not appearing in Django Admin

I am following the official docs of Djongo mapper => https://www.djongomapper.com/using-django-with-mongodb-array-field/ to add Array Fields to my Model, but unfortunately even after adding the Array Fields as stated in the docs I am unable to see them in the below view shown in the docs.
Here is the Model defined by me.
from djongo import models
from django import forms
# Create your models here.
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
class Meta:
abstract = True
def __str__(self):
return self.name
class EventModel(models.Model):
_id = models.ObjectIdField()
authors = models.ArrayField(
model_container=Author,
)
def __str__(self):
return self._id
Here is the generated Django Admin view based on my Models, which is no way similar to the one shown in docs here.
https://www.djongomapper.com/using-django-with-mongodb-array-field/
Any help on this would be appreciated thanks :)

Django admin cannot delete/change instances

I am working on a Django project, and had registered all my models to admin. But due to some reason, I cannot change any of the instances of any model that I created.
This is how it shows:
This is the initial screen as I log in.
As soon as I click on add/change, instead of the usual screen it shows like this:
Here are my models.py and admin.py:
admin.py:
from django.contrib import admin
from .models import Plant, Unit, Equipment, EquipmentCategories, Job, Task_category, Subtask_category, SubtaskStatus, TaskStatus, Files, Filetype, Comment, Timelog, Report, Approvals, Task_flow, Subtask_flow
# Register your models here.
admin.site.register(Plant)
admin.site.register(Unit)
admin.site.register(EquipmentCategories)
admin.site.register(Equipment)
admin.site.register(Job)
admin.site.register(Task_category)
admin.site.register(TaskStatus)
admin.site.register(Subtask_category)
admin.site.register(SubtaskStatus)
admin.site.register(Files)
models.py:
from django.db import models
from django.contrib.auth.models import User
import django.dispatch
# Create your models here.
class Plant(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateField(null=True,blank=True)
end_date = models.DateField(null=True,blank=True)
def __str__(self):
return(self.name)
class Unit(models.Model):
plant = models.ForeignKey(Plant,related_name='Plant', on_delete=models.CASCADE)
name = models.CharField(max_length=200)
unit_location = models.CharField(max_length=200, null=True)
start_date = models.DateField(null=True,blank=True)
end_date = models.DateField(null=True,blank=True)
def __str__(self):
return(self.name)
class EquipmentCategories(models.Model):
unit = models.ForeignKey(Unit,related_name='Unit', on_delete=models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return(self.name)
Can anyone please help!
Thanks in advance :)
I think something is wrong with your STATIC_URL in your settings.py file.
That fixed the issue for me.
It's not finding the right path to your static/admin css and js files.
This problem also occurs when you don't migrate your models properly in the terminal. Make sure to always migrate your models after having modified them.
Will be an issue with your user permissions.
Open the command line and cd /to/your/directory/with/manage.py and run python -m manage createsuperuser
Once you've created that login with those details and you should be able to update things.

DJANGO simplejson

Sorry i'm a beginner in django and python..i create a project and i've a models.py like this:
from django.db import models
class Shoes(models.Model):
type = models.CharField(max_length=30)
start_date = models.DateTimeField()
number = models.IntegerField()
def __unicode__(self):
return str(self.id)
class Meta:
verbose_name_plural = "Shoes"
class Bottom(models.Model):
type = models.CharField(max_length=30)
finish = models.BooleanField()
size = models.IntegerField()
def __unicode__(self):
return str(self.id)
class Meta:
verbose_name_plural = "Bottoms"
class Relation(models.Model):
shoes = models.OneToOneField(Shoes)
bottom = models.ForeignKey(Bottom)
class Meta:
verbose_name_plural = "Relations"
I want to serialize theese classes in json..sorry i need to understand where and how write the specific code to do it..
I wrote already a file views.py and a file.html to view a web page with table of theese objects, but now because i need to write a jquery function that allow to update the web page automatically when i add a new object, I think that we need to serialize the data in json before doing so.
Thanks and bear with me if I said something idiotic because i'm a really beginner in this field..
You want to serialize classes? You want to serialize objects! :) In order to serialize Django objects you can use built-in mechanisms. Read this:
https://docs.djangoproject.com/en/dev/topics/serialization/
For example you can do this like this:
from django.core import serializers
from django.http import HttpResponse
def someView(request):
shoes_from_db = Shoes.objects.all()
json = serializers.serialize(
'json', shoes_from_db, fields=('type','start_date', 'number')
)
return HttpResponse(json, content_type="application/json")

Django ordered ManyToManyField in admin interface

I have a legacy database with tables for documents and authors. A third table defines an ordered many to many relationship between the documents and authors, using foreign keys to the documents and the authors and an integer to specify the author order for a given document.
Using Django 1.1.1 (or SVN), is there a way to edit the document authors and their order in an admin page?
This is quick and a bit rough, but it should get you close(r).
from django.db import models
from django.contrib import admin
class Document(models.Model):
name = models.CharField(max_length = 128)
def __unicode__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length = 128)
document = models.ManyToManyField(Document, through = 'Foo')
def __unicode__(self):
return self.name
class Foo(models.Model):
document = models.ForeignKey(Document)
author = models.ForeignKey(Author)
author_order = models.IntegerField()
class FooInline(admin.TabularInline):
model = Foo
class DocumentAdmin(admin.ModelAdmin):
inlines = [ FooInline ]
admin.site.register(Author)
admin.site.register(Document, DocumentAdmin)
http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects
this might help you too - there is some utility in Django to build models for the legacy databases.
I've built a model for mediawiki database using it. It gets most of the things right, but you'll need to tweak the models a little.