Unable to create Model without fields in Django rest framework - python

I am trying to create a model in Django rest framework, without any field information as I'm using MongoDB which doesn't have any fixed fields
twitterdashmodel.py-----
class TwitterMaster(models.Model):
I need a way out so that I can use model to make query functionality from function based views. I am novice to Django rest framework. Need a guidance/solution to it

You usually write pass [python-doc] to end a scope without any statements:
class TwitterMaster(models.Model):
pass
# … something else …
Note that Django will however add a field itself: an AutoField with the name id that is the primary key of the model. For more information, see the automatic primary key fields section of the documentation.

You can also use Python Doc String
class TwitterMaster(models.Model):
"""TwitterMaster do ...."""

Related

Django - custom getter for 1 field in model

I am writing a model for an external Oracle DB, which I need to pull info from to my project. One of the fields in that Oracle DB is an XMLType, and it hosts large portion of data, which needs to be pulled via .getClobVal() method, instead of querying it straight as it is.
I was wondering, if Django supports any sort of custom logic, for Model's specific fields. Something along the lines of a getter for each field, which I could overwrite to query that specific field as XMLType.getClobVal() instead of just XMLType. At the same time, I don`t want to touch the logic for querying the rest of the Model's fields.
Any ideas?

Django ORM : model with a list of items from another model

In my Django models, I have two models : one called Site and the other SiteFeature.
Object-wise, it is very clear how this should work : every instance of the Site class should have as property a list containing instances of the SiteFeature class, simply because the SiteFeature objects should only exist in relation to a Site object.
Database-wise, it is also very clear how it should work : the SiteFeature table should contain a not-nullable column referencing the primary key id column of the Site table, with a foreign key.
But in terms of Django ORM, I don't know how to code this.
Based on this question, and this other example, it seems the classical way to proceed works the other way round :
The Site model class contains no ORM model field referencing the SiteFeature list.
Instead, the SiteFeature ORM model class has a ForeignKey field referencing the Site class.
I see there is a way to code this out : by adding a function to the Site model class that searches all the related SiteFeature, and make this function a property (decorator #property):
#property
def site_features(self):
return SiteFeature.objects.filter(site_id=site_id)
But that leaves me doubts :
The proper logic for me would also be that when I save, update or create an instance of the Site class, it would also automatically save / update / create the instances of SiteFeature that are related to it. (same thing for deleting the object, but that can be covered by the on_delete=models.CASCADE parameter of the ForeignKey field).
I could add my own save_with_features / update_with_features / create_with_features methods that cascade all but I am not sure what would happen in case of calls made automatically by Django to the standard save / update / create such as in bulk operations.
This problem seems to basic that I suppose there is already a proper way to do it. How would that be ?
Eventually, I solved the problem with the sitefeature_set Manager.
Reference: https://docs.djangoproject.com/en/3.0/topics/db/queries/#following-relationships-backward

Django model on_update=models.CASCADE related object reference

I have looked for django doc in their official site but i can't find the article about the on_update model function here in Related objects reference except for on_delete.
Here is an example code:
from django.db import models
class Reporter(models.Model):
# ...
pass
class Article(models.Model):
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
Is there any version of on_update?
I have visited this Cascade on update and delete wih django but there is not a clear answer about the on_update
I am using mysql and define the relationship in the ERD and sync it to the db and tried running the python manage.py inspectdb to generate the django-model but it shows only models.DO_NOTHING.
Is there a better way to achieve this, if any?
It's normally adviseable to completely leave the primary key alone when setting up your Django models, as these are used by Django in a number of ways to maintain relationships between objects. Django will set them up and use them automatically.
Instead, create a separate field in your model to keep track of unique data:
class Reporter(models.Model):
emp_id = models.CharField(unique=True)
This way you can obtain the emp_id with reporter_object.emp_id and if you need it, you can still get the pk with reporter_object.id.
You can read about how it works it in the Django 1.9 Documentation

Getting Django REST Framework's HyperlinkedModelSerializer to recognize non-default routes

I am in the early stages of a project using Django, Django REST Framework, and SQL. I am very new to DRF.
I have a model that tracks user info for a game service that runs different servers for regions of the world (ex. NA, EU, etc). User IDs are only unique per-region, but the users are all stored using the same model (table). I am employing unique_together = ('user_id', 'region') in my model's Meta class to ensure there are no duplicates. Please note that, as such, the PKs in the DB are not related to the user IDs.
DRF, by default, would create endpoints using the DB's PKs of Users, but I have changed that to use a system like /users/na/123 to get the object where user_id = 123 and region = 'na' (north america). A snippet for this from urls.py follows:
url(r'^users/(?P<region>.+)/$', UserList.as_view()),
url(r'^users/(?P<region>.+)/(?P<user_id>.+$)', UserDetail.as_view()),
These are generic views (generics.ListAPIView and generics.RetrieveAPIView), respectfully.
Currently, the rest of my views are ViewSets.
One of the things I model is historical match data, where users are related to by a Game model, to keep track of who participated in a match like so:
class Game(models.Model):
player_1 = models.ForeignKey(User)
player_2 = models.ForeignKey(User)
I plan on implementing a route for games like I did w/users (again, game_id is unique only per-region) so I can do /game/<region>/<game_id>.
My question is this:
How can I get hyperlinks to Users using my established /user/<region>/<user_id> routes in Game list/detail views on the API?
Presently, my GameSerializer is defined as follows:
class GameSerializer(serializers.ModelSerializer):
class Meta:
model = Game
exclude = ('id',)
When I change it to a HyperlinkedModelSerializer I get the following error upon visiting the Game endpoints:
Could not resolve URL for hyperlinked relationship using view name
"user-detail". You may have failed to include the related model in
your API, or incorrectly configured the lookup_field attribute on
this field.
I assume this is because my User endpoints are implemented differently than what it expects (it can't know I have abandoned the default PK indexing method and opted for a custom route a la /users/<region>/<user_id> instead of /users/<pk>, right?)
How do I approach this problem? I would be open to suggestions that are extraneous to the DRF side of things, like restructuring my DB/Django models, if it seems like the direction I want things to go is crazy (not wanting to use PKs).
After a few more days of reading and thinking about the problem differently, it looks Meta.unique_together is kind of like expressing a composite key in SQL. This lead me to this solution:
https://groups.google.com/forum/#!topic/django-rest-framework/tHmEAzSNgG4
e.g. instead of using an URL like this to identify an employee:
api/1.3/employee/5/
I use an URL like this:
api/1.3/company/23/employee/5/
I use a HyperlinkedModelSerializer to serialise this model. I
couldn't find a way of configuring a HyperlinkedIdentityField to
handle the composite key (you can only specify a single lookup_field)
so I override the url with a SerializerMethodField instead, like this:
class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField('get_employee_detail_url')
def get_employee_detail_url(self, obj):
# generate the URL for the composite key
...
return composite_key_url
Still exploring my options, but this looks pretty clean.
I just came up against the same problem today. After going through the Django-Rest-Framework documentation on Generic views I came across:
lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk'. Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.
http://www.django-rest-framework.org/api-guide/generic-views
In my case I did this in my models.py
class UserDetailView(generics.RetrieveAPIView):
model = User
serializer_class = UserSerializer
lookup_field = "username"
...and works lovely now. Hope that helps.

Create new foreign key in form

I'm using django autocomplete_light and have two models connected via one-to-many relationship. Model A has a ForeignKey field TAG to model B. It all works, but I can only select the existing Tag, it is not possible to automatically add new Tag, even though it is possible to freely type in the box.
How can I "intercept" validation and create the suitable database entry for tag in time?
You could use an add another popup like in django admin.
Here's a live example using this code. The design is not very very good but it demonstrates the point.

Categories