Django, link 2 tables in different database - python

I have 2 DB
Main DB have table for model
class Entry(m.Model):
value = m.CharField(max_length=250, null=True, blank=True)
Seconadry have this
class Feature(m.Model):
linked = m.PositiveIntegerField(default=0)
I need get dictionary like this:
{('entry':'value','linked':'id'),}
Now i get item from second table, iterate, and make list of id's, than take from main DB, and iterate again.
Is there is an options to do this in the right way? Technics, some triks?

You should look into multi-table inheritance which allows you to inherit from multiple parent models. However, I am not 100% sure about it's compatibility with multiple databases.
You would have something like
class Entry(m.Model):
value = m.CharField(max_length=250, null=True, blank=True)
class Feature(m.Model):
linked = m.PositiveIntegerField(default=0)
class EntryFeature(Entry, Feature):
...
There are also alternatives if your schemas can be modified.

Related

django select_related().values() not returning all fields from 2 tables

I have 2 tables, one child (Car) and the other parent (Dealership). I'm using the orm query Car.objects.all().select_related('dealership').values() to perform a left join which would give me all the fields from both cars and their related dealerships but that's not happening as I'm only able to get all the fields from the Car model.
class Dealership(models.Model):
...
class Car(models.Model):
dealership = models.ForeignKey(Dealership, on_delete=models.CASCADE, null=True, default=None)
...
I read it in a different question that with .values() I'll have to explicitly mention all the required fields but there are just too many fields to enter manually. Is there a cleaner solution to this?
select_related is a performance booster and doesn't return you anything more than Car.objects.all() . read about it in https://docs.djangoproject.com/en/3.2/ref/models/querysets/#select-related
You should get dealerships from selected record. for example:
car = Car.objects.select_related('dealership').get(id=1)
dealers = car.dealership
If you are going to return a json from these info, i recommend you to user drf and serializer to handle this

Django - create child models

Let say that the model name is BHA, and I populate this field. In Django-Admin homepage, I will have a tab looks like this:
MY_APP_NAME
BHA List
Other Model 1
Other Model 2
Upon clicking BHA List, I will be navigate to a page that has a list of populated BHA:
BHA List
BHA_1
BHA_2
BHA_3
BHA_4
And each BHA needs a separate table that has their own information. So all BHA's (BHA_1, BHA_2, BHA_3, BHA_4) will have exact same child field Bit data, Sensor Data, Component Data. And Each of these sub-fields will have its own subfields too. How should I design my models.py to make this work? Can anyone provide any example code set that enables this feature?
So far I know only a really basic models.py structure that looks like this:
class SomeModel(models.Model):
field_1 = models.CharField(max_length=100, primary_key=True)
field_2 = models.CharField(max_length=100)
field_3 = models.CharField(max_length=100)
Technically, these are not child classes. They have no inheritance. If I understand you correctly, you will have to use ForeignKey.
BHA(models.Model):
bha_name = models.CharField(params)
BitData(models.Model):
bha = models.ForeignKey(params with reference to BHA)
model_field = models.CharField(params)
SensorData(models.Model):
bha = models.ForeignKey(params with reference to BHA)
model_field = models.CharField(params)
To see them on your page the way you want to will probably involve changing the widget that is used.
You will also have to reference all of your models on the page. Multiple Models Form

Django, treat OneToOne related field as my own field

I'm essentially trying to come up with my own inheritance scheme because Django's inheritance doesn't fit my needs.
I'd like parent table(class) hold common data fields.
sub classess would have its own additional data in a separate table.
class ProductBase(models.Model):
common = models.IntegerField()
def get_price(self):
return some_price
class FooProduct(ProductBase):
# no field because I'm proxy
class Meta:
proxy = True
def get_price(self):
return price_using_different_logic
class FooExtra(models.Model):
base = models.OneToOneField(ProductBase, primary_key=True)
phone = models.CharField(max_length=10)
My question is, would it be able to treat as if Foo has FooExtra's fields?
I'd like to do things like following..
foo = FooProduct.objects.create()
foo.phone = "3333" # as django does with its multiple inheritance
foo.save()
FooProduct.objects.filter(phone="3333")
I'd like to list Products of different kind(data)
I need to list them together, so abstract Base inheritance is out
from the list, I'd like to treat each model as polymorphic model, when iterating over ProductBase.objects.all(), product.get_price() will use appropriate classe's method. (without incurring join if don't have to)
When and only when I want, I retrieve the addtional table data (by something like .select_related('fooextra')
Django-polymorphic is close to what I want, but it is rather obscure what it does so I'm afraid to use it, and I think it fails #3.
If I understand well, you want inheritance and you want the fields that are specific to the child class to be on a separate table.
As far as I know, you don't need a proxy class to achieve that, you could just implement multi-table inheritance as specified in the manual at https://docs.djangoproject.com/en/1.9/topics/db/models/#multi-table-inheritance e.g.:
class Base(models.Model):
common = models.IntegerField()
class Foo(Base):
phone = models.CharField(max_length=10)
This, as explained at the link above, will automatically create a one-to-one relationship. And of course you can do foo.phone = "3333" (where foo is of type Foo) as in your example above. And the neat thing is that you can also access foo.common whereas in your example it would have been foo.base.common.
It doesn't seem like you want anything different to Django's standard inheritance.
class ProductBase(models.Model):
common1 = models.IntegerField()
common2 = models.IntegerField()
class FooProduct(ProductBase):
fooextra = models.IntegerField()
class BarProduct(ProductBase):
barextra = models.IntegerField()
If you create instances of each:
foo1 = FooProduct(common1=1, common2=1, fooextra=1)
foo2 = FooProduct(common1=1, common2=1, fooextra=2)
bar1 = BarProduct(common1=1, common2=1, barextra=1)
bar2 = BarProduct(common1=1, common2=1, barextra=2)
You can loop over all products:
for product in ProductBase.objects.all():
print product.common1, product.common2
From a ProductBase object that is actually a FooProduct, you can get the custom field with:
product.foo.fooextra
From a ProductBase object that is actually a BarProduct, you can get the custom field with:
product.bar.barextra
You can still do querying:
foo = FooProduct.objects.get(fooextra=1)
bar = BarProduct.objects.get(barextra=2)
And you can access the common fields directly on those objects:
foo.common1
bar.common2
You can use the InheritanceManager from django-model-utils if you need more control over querying etc - and this should address point 3, too: ProductBase.objects.filter(...).select_subclasses() would give you the FooProduct and BarProduct objects instead of ProductBase objects.

Nested chain vs duplicated information

There is a models.py with 4 model.
Its standard record is:
class Main(models.Model):
stuff = models.IntegerField()
class Second(models.Model):
nested = models.ForeignKey(Main)
stuff = models.IntegerField()
class Third(models.Model):
nested = models.ForeignKey(Second)
stuff = models.IntegerField()
class Last(models.Model):
nested = models.ForeignKey(Third)
stuff = models.IntegerField()
and there is another variant of Last model:
class Last(models.Model):
nested1 = models.ForeignKey(Main)
nested2 = models.ForeignKey(Second)
nested = models.ForeignKey(Third)
stuff = models.IntegerField()
Will that way save some database load?
The information in nested1 and nested2 will duplicate fields in Secod and Third and even it may become outdated ( fortunately not in my case, as the data will not be changed, only new is added ).
But from my thoughts it may save database load, when I'm looking all Last records for a certain Main record. Or when I'm looking only for Main.id for specific Last item.
Am I right?
Will it really save the load or there is a better practice?
It all depends how you access the data. By default Django will make another call to the database when you access a foreign key. So if you want to make less calls to the database, you can use select_related to prefetch the models in foreign keys.

Django point ForeignKey to an existing relationship table

I am reasonably new to Django and I want to achieve the following: I have a relationship between two tables, say table B has a ManyToMany reference to table A. Now I want a table called Options which saves options to a specific combination between A & B. How do I achieve this?
Thanks!
Hidde
Use the through option of the ManyToMany Field, and add the information in the relationship itself.
For example
class Ingredient(models.Model):
name = models.TextField()
class Recipe(models.Model):
name = models.TextField()
ingredients = models.ManyToManyField(Ingredient, through='RecipePart')
class RecipePart(models.Model)
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
amount = models.IntegerField()
# ...
RecipePart(recipe=pizza, ingredient=cheese, amount=9001).save()
If the relationship already exists (and you already have data) you will have to update the database schema (and create the model if you used to automatic mapping). South can help you do this.

Categories

Resources