How to separate the model into two applications - python

I have one application and one model.
I want to separate the model on two applications, so that the user was managed from a separate application.
Is the transfer of this model will do the trick? What I have to do?
class User(AbstractUser):
country = models.CharField(max_length=2, choices=COUNTRY, default=RUSSIA)
Here is my models.py - must be separate
RUSSIA = 'RUS'
USA = 'USA'
GERMANY = 'GER'
COUNTRY = (
(RUSSIA, "Russia"),
(USA, "USA"),
(GERMANY, "Germany"),
)
class User(AbstractUser):
country = models.CharField(max_length=2, choices=COUNTRY, default=RUSSIA)
class Country(models.Model):
country = models.CharField(max_length=3, choices=COUNTRY, default=RUSSIA)
name_of_team = models.CharField(max_length=255, blank=True, null=True)
def __unicode__(self):
return self.name_of_team

You can create two applications, one for Users and one for Countries. Then put the User model in the Users app and the Country model in the Countries app.
Then in a third app you can import both as you need them:
from countries.models import Country
from users.models import User
Put this part of the code in the settings.py file:
RUSSIA = 'RUS'
USA = 'USA'
GERMANY = 'GER'
COUNTRY = (
(RUSSIA, "Russia"),
(USA, "USA"),
(GERMANY, "Germany"),
)
If you do this then you can access the constants from both apps like this:
from django.conf import settings
settings.COUNTRY

You can create two apps, one for users and one for countries, then you just import country model into user model.
Besides if you want to keep a relationship between countries and user you should use a ForeignKey. Sorry if it does not match with your logic but I'm not sure how your models have to looks like, it is a bit estrange for me.
Something like this:
country/models.py
RUSSIA = 'RUS'
USA = 'USA'
GERMANY = 'GER'
COUNTRY = (
(RUSSIA, "Russia"),
(USA, "USA"),
(GERMANY, "Germany"),
)
class Country(models.Model):
# I don't know why country attr in Country class
country = models.CharField(max_length=3, choices=COUNTRY, default=RUSSIA)
name_of_team = models.CharField(max_length=255, blank=True, null=True)
def __unicode__(self):
return self.name_of_team
user/models.py
from country.models import Country
class User(AbstractUser):
# ForeignKey, here you make the relation with country model
country = models.ForeignKey(Country)

Related

Django-import-export problem importing foreignkey field

I am using the Django-import-export(version 2.5.0) module in Django(version 3.1.4). So I am able to import all my models fields except for the ForeignKey field. I don't know how to make this one work. Can you look at my code and see what is wrong or needs to change? I need Django Admin to import the ForeignKey field.
models.py
# myapp
from django.db import models
from django.contrib.auth.models import User
class Agency(models.Model):
system_name = models.CharField(max_length=255)
county = models.CharField(max_length=60)
state = models.CharField(max_length=2)
active = models.BooleanField(default=True)
system_no = models.CharField(max_length=7, unique=True)
def __str__(self):
return self.system_no
class SitePart(models.Model):
# I tried changing the "system_no" to another name "agency_no" through out the *.py's this did not resolve the problem. Maybe I missed something.
system_no = models.ForeignKey('Agency', on_delete=models.CASCADE, to_field='system_no', null=True, blank=True)
part_name = models.CharField(max_length=125)
status_tuple = [('AB','Abandoned'),('AC','Active Compliant'),('DS','Destroyed'),('IA','Inactive'),
('SB','Stand By waiting acitvation'),('MO','Monitoring')]
status = models.CharField(max_length=2, choices=status_tuple, default= 'SB')
# sys_site_n is unique
sys_site_n = models.CharField(max_length=15, unique=True)
def __str__(self):
return self.part_name
resources.py
from import_export import fields, resources, widgets
from import_export.widgets import ForeignKeyWidget
from myapp.models import Agency, SitePart
class AgencyResource(resources.ModelResource):
class Meta:
model = Agency
import_id_fields = ('system_no',)
fields = ('system_name', 'county', 'state', 'active', 'system_no',)
class SitePartResource(resources.ModelResource):
system_no = fields.Field(
column_name='system_no',
attribute='system_no',
widget=ForeignKeyWidget(Agency,'system_no'))
print(system_no)
class Meta:
model = SitePart
import_id_fields = ('sys_site_n',)
fields = ('system_no','part_name','status', 'sys_site_n',)
admin.py
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from myapp.resources import AgencyResource, SitePartResource
from myapp.models import (Agency, County, SitePart)
class AgencyAdmin(ImportExportModelAdmin):
resource_class = AgencyResource
list_display = ('system_name', 'county', 'state', 'active', 'system_no',)
class SitePartAdmin(ImportExportModelAdmin):
list_display = ('system_no', 'part_name', 'status', 'sys_site_n',)
search_fields = ['system_no',] # Tried removing this, didn't work
resource_class = SitePartResource
admin.site.register(Agency, AgencyAdmin)
admin.site.register(County)
admin.site.register(SitePart, SitePartAdmin)
Agency Table
system_name
county
state
active
system_no
MAGNA SCHOOL
INYO
CA
1
1300553
PINE SCHOOL
INYO
CA
1
1300560
SitePart Table
system_no
part_name
status
sys_site_n
1300553
MAGNA SCHOOL
AC
1300553-01
1300553
Backup Genrtor
SB
1300553-02
1300560
PINE SCHOOL
AC
1300560-01
1300560
Backup Genrtor
SB
1300560-02
When I do import in django admin the system_no is empty.
I don't have the reputation points to be able to add a comment but I think the issue you're experencing is due to your model's field naming conventions.
Since your foreign key relation inside the SitePart to Agency is called system_no, your SitePartResource's ForeignKey Widget isn't referencing the correct field - it's referencing the related Agency model instance (which I believe is why you aren't getting any errors on import but the value is not being displayed).
To fix this, you just neeed to change the ForeignKey widget to reference the related Agency object's system_no field (not the instance itself). I haven't tested it but changing your FK field to something like the following should work!
#resources.py
class SitePartResource(resources.ModelResource):
...
system_no = fields.Field(
column_name='system_no',
attribute='system_no',
widget=ForeignKeyWidget(
Agency,
field='system_no__system_no'
)
)
...
EDIT:
#resources.py
class SitePartResource(resources.ModelResource):
class AgencyForeignKeyWiget(ForeignKeyWidget):
def get_queryset(self, value, row):
return self.model.objects.filter(
system_no__exact=row["system_no"],
)
system_no = fields.Field(
column_name='system_no',
attribute='system_no',
widget=AgencyForeignKeyWidget(
Agency,
field='system_no'
)
)
part_name = fields.Field(column_name="part_name", attribute="part_name")
status = fields.Field(column_name="part_name", attribute="part_name")
sys_site_n = fields.Field(column_name="system_site_n", attribute="system_site_n")
class Meta:
model = SitePart
import_id_fields = ("system_no", "system_site_n")
fields = ('system_no','part_name','status', 'sys_site_n',)

Serializer for fetchiing data from multiple classes

Environment is Python and Django3
I want to make api which retrieve the data from multiple model class.
I have models like this , each CountryStat has Country.
class Country(models.Model):
code = models.CharField(max_length=3,unique=True)
name = models.CharField(max_length=50)
class CountryStat((models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE,null=True)
date = models.DateField(null=True,blank =True)
stat = models.IntegerField()
Now I want to get the latest Coutry Stat for each Country.
So I made the serializer for Country
class CountrySerializer(serializers.ModelSerializer):
latest_stat = serializers.SerializerMethodField()
class Meta:
model = Country
fields = ('id','code','latest_stat')
def get_latest_stat(self,obj):
# how can I get the latest stat from CountryStat model ????
Is this the correct idea or how can I make it??
You should define a custom latest_stat attribute on your model:
class Country(models.Model):
code = models.CharField(max_length=3,unique=True)
name = models.CharField(max_length=50)
def latest_stat(self):
return self.countrystat_set.order_by('-date').first()

How To Do Elastic Search In Model And Related Models In Django

I am using django_elasticsearch_dsl which is running on 9200 port number
and i have two models.
models.py
class Category(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
class Book(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
categories = models.ManyToManyField('Category')
document.py
#posts.doc_type
class PostDocument(DocType):
class Meta:
model = Book
fields = [
'id',
'name'
]
related_models = [Category]
def get_instances_from_related(self, related_instance):
"""If related_models is set, define how to retrieve the book instance(s) from the related model."""
if isinstance(related_instance, Category):
return related_instance.book_set.all()
search.py
from elasticsearch_dsl.query import Q
p = Q("multi_match", query=request.GET.get('q'), fields=['name','categories__name'],
type='phrase_prefix')
s = PostDocument.search().query(p)
result = s.execute()
this search code only works for the books models and i am unable to retrieve using related Category model
my required output should be
like i have two books like jungle and cuop
and jungle book linked to Category model (Category name is sport)
so if search ?q=ju output should show only jungle (working with above code)
and if search ?q=sport output should show only jungle this is not working(it is not giving any results)

GeoDjango: Sort by country of the geolocation

Hi Stackoverflow people,
I have a model which contains projects with the corresponding geolocation:
class Project(models.Model):
name = models.CharField(_('Project Name'), max_length=100, null=True, blank=True)
geolocation = models.PointField(_('Project Location'))
...
In addition, another model is representing a shapefile with the country borders:
class WorldBorder(models.Model):
name = models.CharField(max_length=50)
mpoly = models.MultiPolygonField()
objects = models.GeoManager()
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
How can I do a query on Project and order the results by the country name of the geolocation?
A query like
d = Project.objects.all().order_by(geolocation__name)
does not work since geolocation is not a Foreignkey. Do I really have loop through all projects and determine the country manually like in my example below?
projects = Project.objects.all()
result = []
for project in projects
country = WorldBorder.objects.filter(mpoly__contains = project.geolocation)
foo = [project.name, country]
result.append(foo)
# now sort the list according to the country
result = sorted(result, key=itemgetter(1))
There should be a more professional and elegant solution? Any suggestions from the experienced Python people? Can I use joins for that purpose?
Thank you for your suggestions!

Django Annotations For Group By Through Another Model

I'm having a hard time trying to figure out how to use annotations in the Django ORM to achieve grouping through a model.
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=255)
class Store(models.Model):
name = models.CharField(max_length=255)
class Order(models.Model):
customer = models.ForeignKey(Customer)
store = models.ForeignKey(Store)
order_date = models.DateTimeField()
If my Stores are Los Angeles, Denver, Houston & Atlanta, how do I get a count of
Customers by store using the latest order date?
Los Angeles: 25
Denver: 210
Houston: 400
Atlanta: 6
Define a ManyToMany field on either Customer or Store, pointing to the other model, with Order as the through table. For example:
class Store(models.Model):
name = models.CharField(max_length=255)
orders = models.ManyToManyField(Customer, through=Order)
Now you can do:
from django.db.models import Count
Store.objects.annotate(Count("orders__customer"))

Categories